Import AITURK IDE 1.0.0-beta.1 from Hermes 63279301; preserve MIT license
This commit is contained in:
commit
03634b1ca3
11340 files changed
+3442369
No files matched your search
+259
@@ -0,0 +1,259 @@
|
||||
---
|
||||
title: "Antigravity Cli — Operate the Antigravity CLI (agy): plugins, auth, sandbox"
|
||||
sidebar_label: "Antigravity Cli"
|
||||
description: "Operate the Antigravity CLI (agy): plugins, auth, sandbox"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Antigravity Cli
|
||||
|
||||
Operate the Antigravity CLI (agy): plugins, auth, sandbox.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/autonomous-ai-agents/antigravity-cli` |
|
||||
| Path | `optional-skills/autonomous-ai-agents\antigravity-cli` |
|
||||
| Version | `0.2.0` |
|
||||
| Author | Tony Simons (asimons81), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Coding-Agent`, `Antigravity`, `CLI`, `Auth`, `Plugins`, `Sandbox` |
|
||||
| Related skills | [`grok`](/docs/user-guide/skills/optional/autonomous-ai-agents/autonomous-ai-agents-grok), [`codex`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-codex), [`claude-code`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-claude-code), [`hermes-agent`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Antigravity CLI (`agy`)
|
||||
|
||||
Operator guide for the Antigravity CLI, invoked as `agy`. Run all `agy`
|
||||
commands through the Hermes `terminal` tool; inspect its config and logs with
|
||||
`read_file`. This skill is reference + procedure — it does not wrap a network
|
||||
API, so there is nothing to authenticate from Hermes itself.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Installing, updating, or smoke-testing the `agy` binary
|
||||
- Driving non-interactive `agy --print` / `agy -p` one-shots
|
||||
- Debugging Antigravity auth, sandbox, permissions, or plugin state
|
||||
- Reading Antigravity settings, keybindings, conversations, or logs
|
||||
|
||||
## Mental model
|
||||
|
||||
Antigravity has two layers — keep them distinct or the guidance will be wrong:
|
||||
|
||||
1. **Shell wrapper commands** — `agy help`, `agy install`, `agy plugin`,
|
||||
`agy update`, `agy changelog`. Run these through the `terminal` tool.
|
||||
2. **Interactive in-session slash commands** — `/config`, `/permissions`,
|
||||
`/skills`, `/agents`, etc. These only exist inside a running `agy` TUI
|
||||
session, not on the shell wrapper.
|
||||
|
||||
`agy help` shows the shell wrapper surface, NOT the in-session slash commands.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- The `agy` binary on PATH. Verify through the `terminal` tool:
|
||||
`command -v agy && agy --version`.
|
||||
- No env vars or API keys required by this skill — Antigravity manages its own
|
||||
auth via the OS keyring / browser sign-in (see Authentication below).
|
||||
|
||||
## How to Run
|
||||
|
||||
Invoke every `agy` command through the `terminal` tool. Examples:
|
||||
|
||||
```
|
||||
terminal(command="agy --version")
|
||||
terminal(command="agy help")
|
||||
terminal(command="agy plugin list")
|
||||
terminal(command="agy --print 'Summarize the repo in 3 bullets'", workdir="/path/to/project")
|
||||
```
|
||||
|
||||
For an interactive multi-turn TUI session, launch `agy` with `pty=true` (and
|
||||
tmux for capture/monitoring), the same pattern the `codex` / `claude-code`
|
||||
skills use. For one-shot smoke tests and scripted prompts, prefer
|
||||
`agy --print` (non-interactive).
|
||||
|
||||
To inspect Antigravity's own files, use `read_file` on the paths under Core
|
||||
paths below — do not `cat` them through the terminal.
|
||||
|
||||
## Delegation patterns
|
||||
|
||||
`agy` is a coding-agent backend in the same family as `codex` / `claude-code`,
|
||||
so the same delegation shapes apply. Use these when handing real work (features,
|
||||
fixes, reviews, second opinions) to Antigravity rather than just smoke-testing.
|
||||
|
||||
### One-shot (preferred for scripted prompts and second opinions)
|
||||
|
||||
```
|
||||
terminal(command="agy -p 'Review this diff for bugs and security issues' --model 'Gemini 3.1 Pro (High)'", workdir="/path/to/repo", timeout=300)
|
||||
```
|
||||
|
||||
`-p` is non-interactive: it runs the prompt and exits. Pick the engine with
|
||||
`--model` (run `agy models` for the exact display strings, e.g.
|
||||
`'Gemini 3.1 Pro (High)'`, `'Claude Opus 4.6 (Thinking)'`). Add extra context
|
||||
roots with repeatable `--add-dir`.
|
||||
|
||||
### Long / bounded runs (tests, builds, multi-file changes)
|
||||
|
||||
Background it and get notified on completion, the same as the `codex` skill:
|
||||
|
||||
```
|
||||
terminal(command="agy -p 'Implement the change described in TASK.md and run the tests' --dangerously-skip-permissions", workdir="/path/to/repo", background=true, notify_on_complete=true)
|
||||
# then: process(action="poll"/"log"/"wait", session_id=<id>)
|
||||
```
|
||||
|
||||
### Interactive multi-turn (PTY + tmux)
|
||||
|
||||
For a conversational session, launch `agy -i` (or bare `agy`) under `pty=true`
|
||||
with tmux for `capture-pane` / `send-keys`, exactly the pattern documented in
|
||||
the `codex` / `claude-code` skills. Resume later with `--continue` / `-c` or a
|
||||
specific `--conversation <id>`.
|
||||
|
||||
### Parallel instances (batch sub-issue / worktree fan-out)
|
||||
|
||||
Create one git worktree per task and launch an independent `agy -p` in each
|
||||
(background), then collect results — same worktree fan-out the `codex` skill
|
||||
uses for batch issue fixing. Bound concurrency to what the machine and your
|
||||
review capacity can absorb.
|
||||
|
||||
### Output + bounding caveat (differs from Claude Code)
|
||||
|
||||
- `agy -p` returns **plain text** — there is **no `--output-format json`** and
|
||||
no result envelope with `session_id` / cost / turn count. Parse stdout
|
||||
directly; don't expect a JSON object.
|
||||
- There is **no `--max-turns`**. A print run is bounded by **`--print-timeout`**
|
||||
(default `5m`). Raise it for long tasks: `--print-timeout 20m`. Pair with the
|
||||
`terminal` `timeout=` so the outer call doesn't cut the run short.
|
||||
|
||||
### Orchestration boundary
|
||||
|
||||
Antigravity is a **worker execution backend or third-opinion reviewer** — an
|
||||
execution detail owned by the agent/profile running a task, NOT a first-class
|
||||
orchestration primitive. Do not put `agy` on a kanban board as its own card or
|
||||
treat it as a coordination layer; route work through the normal task graph and
|
||||
let the assigned worker choose `agy` (vs. codex/claude-code/direct tools) as its
|
||||
method. Reach for it explicitly only when the user asks, when a worker is
|
||||
configured to wrap it, or when you want a Gemini-family cross-check against
|
||||
another agent's plan or diff.
|
||||
|
||||
## Core paths
|
||||
|
||||
- Binary / entrypoint: `agy`
|
||||
- App data dir: `~/.gemini/antigravity-cli/`
|
||||
- Settings file: `~/.gemini/antigravity-cli/settings.json`
|
||||
- Keybindings file: `~/.gemini/antigravity-cli/keybindings.json`
|
||||
- Logs: `~/.gemini/antigravity-cli/log/cli-*.log`
|
||||
- Conversations: `~/.gemini/antigravity-cli/conversations/`
|
||||
- Brain artifacts: `~/.gemini/antigravity-cli/brain/`
|
||||
- History: `~/.gemini/antigravity-cli/history.jsonl`
|
||||
- Plugin staging: `~/.gemini/antigravity-cli/plugins/<plugin_name>/`
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Wrapper commands
|
||||
- `agy changelog`
|
||||
- `agy help`
|
||||
- `agy install`
|
||||
- `agy plugin` / `agy plugins`
|
||||
- `agy update`
|
||||
|
||||
### Useful flags
|
||||
- `--add-dir`
|
||||
- `--continue` / `-c`
|
||||
- `--conversation`
|
||||
- `--dangerously-skip-permissions`
|
||||
- `--print` / `-p`
|
||||
- `--print-timeout`
|
||||
- `--prompt`
|
||||
- `--prompt-interactive` / `-i`
|
||||
- `--sandbox`
|
||||
- `--log-file`
|
||||
- `--version`
|
||||
|
||||
### Plugin subcommands (`agy plugin --help`)
|
||||
- `list`, `import [source]`, `install <target>`, `uninstall <name>`,
|
||||
`enable <name>`, `disable <name>`, `validate [path]`, `link <mp> <target>`,
|
||||
`help`
|
||||
|
||||
### Install flags (`agy install --help`)
|
||||
- `--dir`, `--skip-aliases`, `--skip-path`
|
||||
|
||||
### In-session slash commands
|
||||
- **Conversation control:** `/resume` (`/switch`), `/rewind` (`/undo`),
|
||||
`/rename <name>`, `/clear`, `/fork`, `/reset`, `/new`
|
||||
- **Settings & tools:** `/config`, `/settings`, `/permissions`, `/model`,
|
||||
`/keybindings`, `/statusline`, `/tasks`, `/skills`, `/mcp`, `/open <path>`,
|
||||
`/usage`, `/logout`, `/agents`
|
||||
- **Prompt helpers:** `@` path autocomplete, `esc esc` clears the prompt (when
|
||||
not streaming), `!` runs a terminal command directly, `?` opens help
|
||||
|
||||
## Settings and permissions
|
||||
|
||||
### Common settings keys (`settings.json`)
|
||||
- `allowNonWorkspaceAccess`
|
||||
- `colorScheme`
|
||||
- `permissions.allow`
|
||||
- `trustedWorkspaces`
|
||||
|
||||
### Permission modes
|
||||
`request-review`, `always-proceed`, `strict`, `proceed-in-sandbox`.
|
||||
|
||||
### Sandbox behavior
|
||||
- `enableTerminalSandbox` is a boolean in `settings.json`; default `false`.
|
||||
- Launch-time overrides (`--sandbox`, `--dangerously-skip-permissions`) can
|
||||
supersede persistent settings for the current session.
|
||||
|
||||
## Authentication behavior
|
||||
|
||||
- The CLI tries the OS secure keyring first.
|
||||
- With no saved session, it falls back to browser-based Google sign-in.
|
||||
- Locally it opens the default browser; over SSH it prints an authorization URL
|
||||
and expects the auth code pasted back.
|
||||
- `/logout` removes saved credentials.
|
||||
|
||||
## Plugins
|
||||
|
||||
- Plugins stage under `~/.gemini/antigravity-cli/plugins/<plugin_name>/`.
|
||||
- They can bundle skills, agents, rules, MCP servers, and hooks.
|
||||
- `agy plugin list` returning no imported plugins is a valid empty state.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- `agy help` shows wrapper commands, not interactive slash commands.
|
||||
- `agy --version` is the safe non-interactive version check; `agy version` is
|
||||
interactive and can fail without a real TTY.
|
||||
- First place to look for failures: `~/.gemini/antigravity-cli/log/cli-*.log`
|
||||
(read with `read_file`).
|
||||
- Don't confuse persistent JSON settings with launch-time overrides.
|
||||
- `~/.gemini/antigravity-cli/bin/agentapi` is a thin wrapper to `agy agentapi`.
|
||||
- On WSL, token storage is file-based, so auth issues are usually local-file /
|
||||
session-state problems, not browser-only problems.
|
||||
- Workspace identity can depend on launch directory and the `.antigravitycli`
|
||||
project marker.
|
||||
- `agy -p` prints plain text only — no `--output-format json`, no result
|
||||
envelope. Don't try to parse a JSON object out of it (unlike `claude-code`).
|
||||
- Bound print runs with `--print-timeout` (default `5m`), not `--max-turns`
|
||||
(which does not exist on `agy`).
|
||||
|
||||
## Verification
|
||||
|
||||
Confirm the install is real and usable, all through the `terminal` tool (read
|
||||
files with `read_file`):
|
||||
|
||||
1. `terminal(command="command -v agy")`
|
||||
2. `terminal(command="agy --version")`
|
||||
3. `terminal(command="agy help")`
|
||||
4. `terminal(command="agy plugin list")`
|
||||
5. `read_file` on `~/.gemini/antigravity-cli/settings.json`
|
||||
6. `read_file` on the latest `~/.gemini/antigravity-cli/log/cli-*.log`
|
||||
7. If needed, `read_file` on `~/.gemini/antigravity-cli/keybindings.json`
|
||||
|
||||
## Support files
|
||||
|
||||
- `references/cli-docs.md` — condensed notes from the getting-started, usage,
|
||||
and features docs.
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
---
|
||||
title: "Blackbox — Delegate coding tasks to the Blackbox AI multi-model CLI"
|
||||
sidebar_label: "Blackbox"
|
||||
description: "Delegate coding tasks to the Blackbox AI multi-model CLI"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Blackbox
|
||||
|
||||
Delegate coding tasks to the Blackbox AI multi-model CLI.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/autonomous-ai-agents/blackbox` |
|
||||
| Path | `optional-skills/autonomous-ai-agents\blackbox` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Hermes Agent (Nous Research) |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Coding-Agent`, `Blackbox`, `Multi-Agent`, `Judge`, `Multi-Model` |
|
||||
| Related skills | [`claude-code`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-claude-code), [`codex`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-codex), [`hermes-agent`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Blackbox CLI
|
||||
|
||||
Delegate coding tasks to [Blackbox AI](https://www.blackbox.ai/) via the Hermes terminal. Blackbox is a multi-model coding agent CLI that dispatches tasks to multiple LLMs (Claude, Codex, Gemini, Blackbox Pro) and uses a judge to select the best implementation.
|
||||
|
||||
The CLI (npm `@blackbox_ai/blackbox-cli`, binary `blackbox`) is a TypeScript coding agent (forked from Gemini CLI) and supports interactive sessions, non-interactive one-shots, checkpointing, MCP, and vision model switching.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 20+ installed
|
||||
- Blackbox CLI installed: `npm install -g @blackbox_ai/blackbox-cli` (binary: `blackbox`)
|
||||
- API key from [app.blackbox.ai/dashboard](https://app.blackbox.ai/dashboard)
|
||||
- Configured: run `blackbox configure` and enter your API key
|
||||
- Use `pty=true` in terminal calls — Blackbox CLI is an interactive terminal app
|
||||
|
||||
## One-Shot Tasks
|
||||
|
||||
```
|
||||
terminal(command="blackbox --prompt 'Add JWT authentication with refresh tokens to the Express API'", workdir="/path/to/project", pty=true)
|
||||
```
|
||||
|
||||
For quick scratch work:
|
||||
```
|
||||
terminal(command="cd $(mktemp -d) && git init && blackbox --prompt 'Build a REST API for todos with SQLite'", pty=true)
|
||||
```
|
||||
|
||||
## Background Mode (Long Tasks)
|
||||
|
||||
For tasks that take minutes, use background mode so you can monitor progress:
|
||||
|
||||
```
|
||||
# Start in background with PTY
|
||||
terminal(command="blackbox --prompt 'Refactor the auth module to use OAuth 2.0'", workdir="~/project", background=true, pty=true)
|
||||
# Returns session_id
|
||||
|
||||
# Monitor progress
|
||||
process(action="poll", session_id="<id>")
|
||||
process(action="log", session_id="<id>")
|
||||
|
||||
# Send input if Blackbox asks a question
|
||||
process(action="submit", session_id="<id>", data="yes")
|
||||
|
||||
# Kill if needed
|
||||
process(action="kill", session_id="<id>")
|
||||
```
|
||||
|
||||
## Checkpoints & Resume
|
||||
|
||||
Blackbox CLI has built-in checkpoint support for pausing and resuming tasks:
|
||||
|
||||
```
|
||||
# After a task completes, Blackbox shows a checkpoint tag
|
||||
# Resume with a follow-up task:
|
||||
terminal(command="blackbox --resume-checkpoint 'task-abc123-2026-03-06' --prompt 'Now add rate limiting to the endpoints'", workdir="~/project", pty=true)
|
||||
```
|
||||
|
||||
## Session Commands
|
||||
|
||||
During an interactive session, use these commands:
|
||||
|
||||
| Command | Effect |
|
||||
|---------|--------|
|
||||
| `/compress` | Shrink conversation history to save tokens |
|
||||
| `/clear` | Wipe history and start fresh |
|
||||
| `/stats` | View current token usage |
|
||||
| `Ctrl+C` | Cancel current operation |
|
||||
|
||||
## PR Reviews
|
||||
|
||||
Clone to a temp directory to avoid modifying the working tree:
|
||||
|
||||
```
|
||||
terminal(command="REVIEW=$(mktemp -d) && git clone https://github.com/user/repo.git $REVIEW && cd $REVIEW && gh pr checkout 42 && blackbox --prompt 'Review this PR against main. Check for bugs, security issues, and code quality.'", pty=true)
|
||||
```
|
||||
|
||||
## Parallel Work
|
||||
|
||||
Spawn multiple Blackbox instances for independent tasks:
|
||||
|
||||
```
|
||||
terminal(command="blackbox --prompt 'Fix the login bug'", workdir="/tmp/issue-1", background=true, pty=true)
|
||||
terminal(command="blackbox --prompt 'Add unit tests for auth'", workdir="/tmp/issue-2", background=true, pty=true)
|
||||
|
||||
# Monitor all
|
||||
process(action="list")
|
||||
```
|
||||
|
||||
## Multi-Model Mode
|
||||
|
||||
Blackbox's unique feature is running the same task through multiple models and judging the results. Configure which models to use via `blackbox configure` — select multiple providers to enable the Chairman/judge workflow where the CLI evaluates outputs from different models and picks the best one.
|
||||
|
||||
## Key Flags
|
||||
|
||||
| Flag | Effect |
|
||||
|------|--------|
|
||||
| `--prompt "task"` (`-p`) | Non-interactive one-shot execution |
|
||||
| `--resume-checkpoint "tag"` | Resume from a saved checkpoint |
|
||||
| `--yolo` (`-y`) | Auto-approve all actions and model switches |
|
||||
| `--vlm-switch-mode <mode>` | Image-handling: `once`, `session`, or `persist` |
|
||||
| `-c, --checkpointing` | Enable checkpointing of file edits |
|
||||
| `blackbox configure` | Change settings, providers, models |
|
||||
| `blackbox update` | Update the CLI to the latest version |
|
||||
| `blackbox mcp` | Manage MCP servers |
|
||||
| `blackbox extensions` | Manage CLI extensions |
|
||||
| `blackbox voice <action>` / `blackbox shortcut` | Configure voice input / the `b` shortcut |
|
||||
|
||||
## Vision Support
|
||||
|
||||
Blackbox automatically detects images in input and can switch to multimodal analysis. VLM modes:
|
||||
- `"once"` — Switch model for current query only
|
||||
- `"session"` — Switch for entire session
|
||||
- `"persist"` — Stay on current model (no switch)
|
||||
|
||||
## Token Limits
|
||||
|
||||
Control token usage via `.blackboxcli/settings.json`:
|
||||
```json
|
||||
{
|
||||
"sessionTokenLimit": 32000
|
||||
}
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
1. **Always use `pty=true`** — Blackbox CLI is an interactive terminal app and will hang without a PTY
|
||||
2. **Use `workdir`** — keep the agent focused on the right directory
|
||||
3. **Background for long tasks** — use `background=true` and monitor with `process` tool
|
||||
4. **Don't interfere** — monitor with `poll`/`log`, don't kill sessions because they're slow
|
||||
5. **Report results** — after completion, check what changed and summarize for the user
|
||||
6. **Credits cost money** — Blackbox uses a credit-based system; multi-model mode consumes credits faster
|
||||
7. **Check prerequisites** — verify `blackbox` CLI is installed before attempting delegation
|
||||
+326
@@ -0,0 +1,326 @@
|
||||
---
|
||||
title: "Grok — Delegate coding to xAI Grok Build CLI (features, PRs)"
|
||||
sidebar_label: "Grok"
|
||||
description: "Delegate coding to xAI Grok Build CLI (features, PRs)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Grok
|
||||
|
||||
Delegate coding to xAI Grok Build CLI (features, PRs).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/autonomous-ai-agents/grok` |
|
||||
| Path | `optional-skills/autonomous-ai-agents\grok` |
|
||||
| Version | `0.1.1` |
|
||||
| Author | Matt Maximo (MattMaximo), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Coding-Agent`, `Grok`, `xAI`, `Code-Review`, `Refactoring`, `Automation` |
|
||||
| Related skills | [`codex`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-codex), [`claude-code`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-claude-code), [`hermes-agent`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Grok Build CLI — Hermes Orchestration Guide
|
||||
|
||||
Delegate coding tasks to [Grok Build](https://docs.x.ai/build/overview) (xAI's
|
||||
autonomous coding agent CLI, the `grok` command) via the Hermes terminal. Grok
|
||||
can read files, write code, run shell commands, spawn subagents, and manage git
|
||||
workflows. It runs three ways: an interactive TUI, **headless** (`-p`), and as
|
||||
an **ACP agent** over JSON-RPC.
|
||||
|
||||
This is the third sibling to `codex` and `claude-code`. The orchestration
|
||||
pattern is nearly identical — **prefer headless `-p` for one-shots**, use a PTY
|
||||
for interactive sessions.
|
||||
|
||||
## When to use
|
||||
|
||||
- Building features
|
||||
- Refactoring
|
||||
- PR reviews
|
||||
- Batch issue fixing
|
||||
- Any task where you'd otherwise reach for Codex / Claude Code but want Grok
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Install (preferred):** `npm install -g @xai-official/grok`
|
||||
- The official installer `curl -fsSL https://x.ai/cli/install.sh | bash` also
|
||||
works, but the `x.ai` host is Cloudflare-walled in some environments. The
|
||||
npm path avoids that dependency entirely.
|
||||
- **Auth — SuperGrok / X Premium+ subscription (primary path):**
|
||||
- Run `grok login` once → opens a browser for OAuth → token cached in
|
||||
`~/.grok/auth.json`. This uses your **SuperGrok or X Premium+** subscription
|
||||
(no per-token API billing).
|
||||
- Check sign-in state by looking for `~/.grok/auth.json`, or run a cheap
|
||||
headless smoke test: `grok --no-auto-update -p "Say ok."`
|
||||
- In the TUI, `/logout` signs out and `/login` (or relaunching) signs back in.
|
||||
- **No git repo required** — unlike Codex, Grok runs fine outside a git
|
||||
directory (good for scratch/throwaway tasks).
|
||||
- **Claude Code / AGENTS.md compatible with zero config** — Grok auto-reads
|
||||
`CLAUDE.md`, `.claude/` (skills, agents, MCPs, hooks, rules), and the
|
||||
`AGENTS.md` family. Existing project context just works.
|
||||
|
||||
> **API-key fallback (not the default for this user):** Grok also supports
|
||||
> setting the `XAI_API_KEY` environment variable for pay-as-you-go billing
|
||||
> via `api.x.ai`. Only use
|
||||
> this if `grok login` / SuperGrok auth is unavailable. The subscription path
|
||||
> (`grok login`) is the intended setup here.
|
||||
|
||||
## Two Orchestration Modes
|
||||
|
||||
### Mode 1: Headless (`-p`) — Non-Interactive (PREFERRED)
|
||||
|
||||
Runs a one-shot task, prints the result, and exits. No PTY, no interactive
|
||||
dialogs to navigate. This is the cleanest integration path — the analog of
|
||||
`claude -p` and `codex exec`.
|
||||
|
||||
```
|
||||
terminal(command="grok --no-auto-update -p 'Add a dark mode toggle to settings'", workdir="/path/to/project", timeout=180)
|
||||
```
|
||||
|
||||
Always pass `--no-auto-update` in automation to skip background update checks.
|
||||
|
||||
**When to use headless:**
|
||||
- One-shot coding tasks (fix a bug, add a feature, refactor)
|
||||
- CI/CD automation and scripting
|
||||
- Structured output parsing with `--output-format json`
|
||||
- Any task that doesn't need multi-turn conversation
|
||||
|
||||
### Mode 2: Interactive PTY — Multi-Turn TUI Sessions
|
||||
|
||||
The TUI is a fullscreen, mouse-interactive app. Drive it with `pty=true`. For
|
||||
robust monitoring/input use tmux (same pattern as the `claude-code` skill).
|
||||
|
||||
```
|
||||
# Launch in a tmux session for capture-pane monitoring
|
||||
terminal(command="tmux new-session -d -s grok-work -x 140 -y 40")
|
||||
terminal(command="tmux send-keys -t grok-work 'cd /path/to/project && grok' Enter")
|
||||
|
||||
# Wait for startup, then send a task
|
||||
terminal(command="sleep 5 && tmux send-keys -t grok-work 'Refactor the auth module to use JWT' Enter")
|
||||
|
||||
# Monitor progress
|
||||
terminal(command="sleep 15 && tmux capture-pane -t grok-work -p -S -50")
|
||||
|
||||
# Exit when done
|
||||
terminal(command="tmux send-keys -t grok-work '/quit' Enter && sleep 1 && tmux kill-session -t grok-work")
|
||||
```
|
||||
|
||||
**Tip for headless-but-inline output:** if you want TUI-style output without the
|
||||
fullscreen alt-screen takeover (e.g. for cleaner logs), add `--no-alt-screen`.
|
||||
For pure automation, headless `-p` is still cleaner than the TUI.
|
||||
|
||||
## Headless Deep Dive
|
||||
|
||||
### Common Flags
|
||||
|
||||
| Flag | Effect |
|
||||
|------|--------|
|
||||
| `-p, --single <PROMPT>` | Send one prompt, run headless, exit |
|
||||
| `-m, --model <MODEL>` | Choose a model |
|
||||
| `-s, --session-id <UUID>` | Assign a **NEW** valid UUID to a fresh conversation (must not already exist). Does **not** resume — use `--resume`/`--continue` for that. Only valid with `--resume`/`--continue` when paired with `--fork-session` |
|
||||
| `-r, --resume [<UUID>]` | Resume an existing session by its UUID (or the most recent if omitted) |
|
||||
| `-c, --continue` | Continue the most recent session in the current directory |
|
||||
| `--fork-session` | When resuming, create a new session ID instead of reusing the original |
|
||||
| `--max-turns <N>` | Cap the maximum number of agent turns |
|
||||
| `--cwd <PATH>` | Set the working directory |
|
||||
| `--output-format <FMT>` | `plain` (default), `json`, or `streaming-json` |
|
||||
| `--always-approve` | Auto-approve all tool executions (the `--full-auto` / `--yolo` equivalent) |
|
||||
| `--no-alt-screen` | Run inline, no fullscreen TUI takeover |
|
||||
| `--no-auto-update` | Skip background update checks (use in all automation; hidden from `--help` but still works) |
|
||||
|
||||
### Output Formats
|
||||
|
||||
- `plain` — human-readable text (default)
|
||||
- `json` — one JSON object at the end of the run (parse the result cleanly)
|
||||
- `streaming-json` — newline-delimited JSON events as they arrive
|
||||
|
||||
```
|
||||
# Structured result for parsing
|
||||
terminal(command="grok --no-auto-update -p 'List all TODO comments in src/' --output-format json", workdir="/project", timeout=120)
|
||||
|
||||
# Auto-approve for autonomous building
|
||||
terminal(command="grok --no-auto-update --always-approve -p 'Refactor the database layer and run the tests'", workdir="/project", timeout=300)
|
||||
```
|
||||
|
||||
### Background Mode (Long Tasks)
|
||||
|
||||
```
|
||||
# Start headless in background
|
||||
terminal(command="grok --no-auto-update --always-approve -p 'Refactor the auth module'", workdir="/project", background=true, notify_on_complete=true)
|
||||
# Returns session_id
|
||||
|
||||
# Monitor
|
||||
process(action="poll", session_id="<id>")
|
||||
process(action="log", session_id="<id>")
|
||||
|
||||
# Kill if needed
|
||||
process(action="kill", session_id="<id>")
|
||||
```
|
||||
|
||||
For an interactive (TUI) background session, use `pty=true` + tmux and monitor
|
||||
with `tmux capture-pane`, exactly like the `claude-code` / `codex` skills.
|
||||
|
||||
### Session Continuation
|
||||
|
||||
Sessions are keyed by **UUID**, not by name. `--session-id` assigns a *new* UUID
|
||||
to a fresh run (it does **not** resume); `--resume` takes an existing session's
|
||||
UUID (or omit the value to resume the most recent).
|
||||
|
||||
```
|
||||
# Start a session with a self-assigned UUID (must be a valid, unused UUID)
|
||||
SID=$(uuidgen)
|
||||
terminal(command="grok --no-auto-update -s $SID -p 'Start refactoring the database layer' --always-approve", workdir="/project", timeout=240)
|
||||
|
||||
# Resume that exact session later by its UUID
|
||||
terminal(command="grok --no-auto-update -r $SID -p 'Now add connection pooling' --always-approve", workdir="/project", timeout=180)
|
||||
|
||||
# Or just continue the most recent session in this directory (no UUID needed)
|
||||
terminal(command="grok --no-auto-update -c -p 'What did you change last time?'", workdir="/project", timeout=60)
|
||||
```
|
||||
|
||||
## Read-Only Audit → Markdown Note Pattern
|
||||
|
||||
To have Grok review local artifacts and return a clean markdown note (for
|
||||
Obsidian or a repo) without mutating anything:
|
||||
|
||||
1. Prepare stable input files first with Hermes tools (`read_file`,
|
||||
`write_file`). Snapshot only the relevant context into a temp file rather
|
||||
than dumping raw paths.
|
||||
2. Run Grok headless **without** `--always-approve` so it cannot auto-write, and
|
||||
demand `markdown only, no preamble`.
|
||||
3. Save Grok's stdout straight into the destination note with `write_file()`.
|
||||
|
||||
```
|
||||
grok --no-auto-update -p "Read /tmp/current.md and /tmp/inventory.md. Produce markdown only, no preamble. Output a clean note titled 'Cleanup Review'." --output-format plain
|
||||
```
|
||||
|
||||
**Pitfall (same as Claude Code):** for document rewrites, a loose "rewrite this"
|
||||
prompt may return a change summary instead of the full file. Instead: pipe the
|
||||
file in, and demand `Return ONLY the full revised markdown document. No intro,
|
||||
no explanation, no code fences. Start immediately with '# Title'.` Verify the
|
||||
first lines with `read_file()` before overwriting the destination.
|
||||
|
||||
## PR Review Patterns
|
||||
|
||||
### Quick Review (Headless)
|
||||
|
||||
```
|
||||
terminal(command="cd /path/to/repo && git diff main...feature-branch | grok --no-auto-update -p 'Review this diff for bugs, security issues, and style problems. Be thorough.'", timeout=120)
|
||||
```
|
||||
|
||||
### Clone-to-temp Review (safe, no repo mutation)
|
||||
|
||||
```
|
||||
terminal(command="REVIEW=$(mktemp -d) && git clone https://github.com/user/repo.git $REVIEW && cd $REVIEW && gh pr checkout 42 && grok --no-auto-update -p 'Review the changes vs origin/main. Check bugs, security, race conditions, missing tests.'", pty=true, timeout=300)
|
||||
```
|
||||
|
||||
### Post the review
|
||||
|
||||
```
|
||||
terminal(command="gh pr comment 42 --body '<review text>'", workdir="/path/to/repo")
|
||||
```
|
||||
|
||||
## Parallel Issue Fixing with Worktrees
|
||||
|
||||
```
|
||||
# Create worktrees
|
||||
terminal(command="git worktree add -b fix/issue-78 /tmp/issue-78 main", workdir="~/project")
|
||||
terminal(command="git worktree add -b fix/issue-99 /tmp/issue-99 main", workdir="~/project")
|
||||
|
||||
# Launch Grok headless in each (background)
|
||||
terminal(command="grok --no-auto-update --always-approve -p 'Fix issue #78: <description>. Commit when done.'", workdir="/tmp/issue-78", background=true, notify_on_complete=true)
|
||||
terminal(command="grok --no-auto-update --always-approve -p 'Fix issue #99: <description>. Commit when done.'", workdir="/tmp/issue-99", background=true, notify_on_complete=true)
|
||||
|
||||
# Monitor
|
||||
process(action="list")
|
||||
|
||||
# After completion: push and open PRs
|
||||
terminal(command="cd /tmp/issue-78 && git push -u origin fix/issue-78")
|
||||
terminal(command="gh pr create --repo user/repo --head fix/issue-78 --title 'fix: ...' --body '...'")
|
||||
|
||||
# Cleanup
|
||||
terminal(command="git worktree remove /tmp/issue-78", workdir="~/project")
|
||||
```
|
||||
|
||||
## Useful Subcommands & TUI Commands
|
||||
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `grok` | Start the interactive TUI |
|
||||
| `grok -p "query"` | Headless one-shot |
|
||||
| `grok login` / `grok logout` | Sign in / out (SuperGrok / X Premium+ OAuth) |
|
||||
| `grok inspect` | Show what Grok discovered in cwd: config sources, instructions, skills, plugins, hooks, MCP servers |
|
||||
| `grok agent stdio` | Run as an ACP agent over JSON-RPC (for IDE/tool integration) |
|
||||
| `grok update` | Update the CLI (needs the `x.ai` host; skip in automation) |
|
||||
|
||||
TUI slash commands (interactive only): `/model <name>`, `/always-approve`,
|
||||
`/plan`, `/context`, `/compact`, `/resume`, `/sessions`, `/fork`, `/usage`,
|
||||
`/quit`. `Shift+Tab` cycles session modes (including Plan mode, which blocks
|
||||
write tools except the session plan file).
|
||||
|
||||
## Config (`~/.grok/config.toml`)
|
||||
|
||||
```toml
|
||||
[cli]
|
||||
auto_update = false # skip background update checks persistently
|
||||
|
||||
[ui]
|
||||
permission_mode = "ask" # or "always-approve" to skip tool prompts by default
|
||||
|
||||
[models]
|
||||
default = "grok-build-0.1"
|
||||
```
|
||||
|
||||
Put global preferences in `~/.grok/config.toml` (not project-scoped
|
||||
`.grok/config.toml`). `permission_mode` supersedes the legacy `approval_mode` /
|
||||
`yolo = true` keys.
|
||||
|
||||
## Pitfalls & Gotchas
|
||||
|
||||
1. **Auth is subscription-gated.** `grok login` requires a SuperGrok or X
|
||||
Premium+ subscription. If login fails or there's no `~/.grok/auth.json`,
|
||||
confirm the subscription is active before falling back to `XAI_API_KEY`.
|
||||
2. **Don't conflate Hermes' xAI auth with the `grok` CLI's auth.** Hermes'
|
||||
`x_search` runs on its own xAI OAuth; the standalone `grok` CLI has a
|
||||
separate token in `~/.grok/auth.json`. A working `x_search` does NOT mean
|
||||
`grok` is logged in.
|
||||
3. **Always pass `--no-auto-update` in automation** — otherwise Grok phones home
|
||||
for update checks (and `x.ai`/`storage.googleapis.com` may be unreachable).
|
||||
4. **Prefer npm install over the curl installer** — `npm install -g
|
||||
@xai-official/grok` avoids the Cloudflare-walled `x.ai` host.
|
||||
5. **`--always-approve` is the autonomous-build switch.** Without it, headless
|
||||
runs may stall waiting on tool-approval prompts. Omit it deliberately for
|
||||
read-only review/audit work so Grok can't mutate files.
|
||||
6. **Headless `-p` skips TUI dialogs**; the TUI needs `pty=true` (+ tmux for
|
||||
monitoring), just like Claude Code.
|
||||
7. **Use `--no-alt-screen`** if you run the TUI inline and the fullscreen
|
||||
alt-screen takeover garbles captured output.
|
||||
8. **No git repo needed**, but for PR/commit workflows you still want one — use
|
||||
`mktemp -d && git init` for scratch commit tasks.
|
||||
9. **Clean up tmux sessions** with `tmux kill-session -t <name>` when done.
|
||||
|
||||
## Rules for Hermes Agents
|
||||
|
||||
1. **Prefer headless `-p`** for single tasks — cleanest integration, structured
|
||||
output via `--output-format json`.
|
||||
2. **Always set `workdir`** (or `--cwd`) so Grok targets the right project.
|
||||
3. **Pass `--no-auto-update`** in every automated invocation.
|
||||
4. **Use `--always-approve` only when Grok should write autonomously**; omit it
|
||||
for read-only reviews and audits.
|
||||
5. **Background long tasks** with `background=true, notify_on_complete=true` and
|
||||
monitor via the `process` tool.
|
||||
6. **Use tmux for multi-turn interactive work** and monitor with
|
||||
`tmux capture-pane -t <session> -p -S -50`.
|
||||
7. **Verify auth before relying on it** — check `~/.grok/auth.json` or run a
|
||||
cheap `grok -p "Say ok."` smoke test; don't assume Hermes' xAI auth carries
|
||||
over.
|
||||
8. **Report results to the user** — summarize what Grok changed and what's left.
|
||||
+446
@@ -0,0 +1,446 @@
|
||||
---
|
||||
title: "Honcho — Configure and troubleshoot Honcho memory for Hermes"
|
||||
sidebar_label: "Honcho"
|
||||
description: "Configure and troubleshoot Honcho memory for Hermes"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Honcho
|
||||
|
||||
Configure and troubleshoot Honcho memory for Hermes.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/autonomous-ai-agents/honcho` |
|
||||
| Path | `optional-skills/autonomous-ai-agents\honcho` |
|
||||
| Version | `2.0.0` |
|
||||
| Author | Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Honcho`, `Memory`, `Profiles`, `Observation`, `Dialectic`, `User-Modeling`, `Session-Summary` |
|
||||
| Related skills | [`hermes-agent`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Honcho Memory for Hermes
|
||||
|
||||
Honcho provides AI-native cross-session user modeling. It learns who the user is across conversations and gives every Hermes profile its own peer identity while sharing a unified view of the user.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Setting up Honcho (cloud or self-hosted)
|
||||
- Troubleshooting memory not working / peers not syncing
|
||||
- Creating multi-profile setups where each agent has its own Honcho peer
|
||||
- Tuning observation, recall, dialectic depth, or write frequency settings
|
||||
- Understanding what the 5 Honcho tools do and when to use them
|
||||
- Configuring context budgets and session summary injection
|
||||
|
||||
## Setup
|
||||
|
||||
### Cloud (app.honcho.dev)
|
||||
|
||||
```bash
|
||||
hermes memory setup honcho
|
||||
# select "cloud", paste API key from https://app.honcho.dev
|
||||
```
|
||||
|
||||
### Self-hosted
|
||||
|
||||
```bash
|
||||
hermes memory setup honcho
|
||||
# select "local", enter base URL (e.g. http://localhost:8000)
|
||||
```
|
||||
|
||||
See: https://docs.honcho.dev/v3/guides/integrations/hermes#running-honcho-locally-with-hermes
|
||||
|
||||
### Verify
|
||||
|
||||
```bash
|
||||
hermes honcho status # shows resolved config, connection test, peer info
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Base Context Injection
|
||||
|
||||
When Honcho injects context into the system prompt (in `hybrid` or `context` recall modes), it assembles the base context block in this order:
|
||||
|
||||
1. **Session summary** -- a short digest of the current session so far (placed first so the model has immediate conversational continuity)
|
||||
2. **User representation** -- Honcho's accumulated model of the user (preferences, facts, patterns)
|
||||
3. **AI peer card** -- the identity card for this Hermes profile's AI peer
|
||||
|
||||
The session summary is generated automatically by Honcho at the start of each turn (when a prior session exists). It gives the model a warm start without replaying full history.
|
||||
|
||||
### Cold / Warm Prompt Selection
|
||||
|
||||
Honcho automatically selects between two prompt strategies:
|
||||
|
||||
| Condition | Strategy | What happens |
|
||||
|-----------|----------|--------------|
|
||||
| No prior session or empty representation | **Cold start** | Lightweight intro prompt; skips summary injection; encourages the model to learn about the user |
|
||||
| Existing representation and/or session history | **Warm start** | Full base context injection (summary → representation → card); richer system prompt |
|
||||
|
||||
You do not need to configure this -- it is automatic based on session state.
|
||||
|
||||
### Peers
|
||||
|
||||
Honcho models conversations as interactions between **peers**. Hermes creates two peers per session:
|
||||
|
||||
- **User peer** (`peerName`): represents the human. Honcho builds a user representation from observed messages.
|
||||
- **AI peer** (`aiPeer`): represents this Hermes instance. Each profile gets its own AI peer so agents develop independent views.
|
||||
|
||||
### Observation
|
||||
|
||||
Each peer has two observation toggles that control what Honcho learns from:
|
||||
|
||||
| Toggle | What it does |
|
||||
|--------|-------------|
|
||||
| `observeMe` | Peer's own messages are observed (builds self-representation) |
|
||||
| `observeOthers` | Other peers' messages are observed (builds cross-peer understanding) |
|
||||
|
||||
Default: all four toggles **on** (full bidirectional observation).
|
||||
|
||||
Configure per-peer in `honcho.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"observation": {
|
||||
"user": { "observeMe": true, "observeOthers": true },
|
||||
"ai": { "observeMe": true, "observeOthers": true }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Or use the shorthand presets:
|
||||
|
||||
| Preset | User | AI | Use case |
|
||||
|--------|------|----|----------|
|
||||
| `"directional"` (default) | me:on, others:on | me:on, others:on | Multi-agent, full memory |
|
||||
| `"unified"` | me:on, others:off | me:off, others:on | Single agent, user-only modeling |
|
||||
|
||||
Settings changed in the [Honcho dashboard](https://app.honcho.dev) are synced back on session init -- server-side config wins over local defaults.
|
||||
|
||||
### Sessions
|
||||
|
||||
Honcho sessions scope where messages and observations land. Strategy options:
|
||||
|
||||
| Strategy | Behavior |
|
||||
|----------|----------|
|
||||
| `per-directory` (default) | One session per working directory |
|
||||
| `per-repo` | One session per git repository root |
|
||||
| `per-session` | New Honcho session each Hermes run |
|
||||
| `global` | Single session across all directories |
|
||||
|
||||
Manual override: `hermes honcho map my-project-name`
|
||||
|
||||
### Recall Modes
|
||||
|
||||
How the agent accesses Honcho memory:
|
||||
|
||||
| Mode | Auto-inject context? | Tools available? | Use case |
|
||||
|------|---------------------|-----------------|----------|
|
||||
| `hybrid` (default) | Yes | Yes | Agent decides when to use tools vs auto context |
|
||||
| `context` | Yes | No (hidden) | Minimal token cost, no tool calls |
|
||||
| `tools` | No | Yes | Agent controls all memory access explicitly |
|
||||
|
||||
## Three Orthogonal Knobs
|
||||
|
||||
Honcho's dialectic behavior is controlled by three independent dimensions. Each can be tuned without affecting the others:
|
||||
|
||||
### Cadence (when)
|
||||
|
||||
Controls **how often** dialectic and context calls happen.
|
||||
|
||||
| Key | Default | Description |
|
||||
|-----|---------|-------------|
|
||||
| `contextCadence` | `1` | Min turns between context API calls |
|
||||
| `dialecticCadence` | `2` | Min turns between dialectic API calls. Recommended 1–5 |
|
||||
| `injectionFrequency` | `every-turn` | `every-turn` or `first-turn` for base context injection |
|
||||
|
||||
Higher cadence values fire the dialectic LLM less often. `dialecticCadence: 2` means the engine fires every other turn. Setting it to `1` fires every turn.
|
||||
|
||||
### Depth (how many)
|
||||
|
||||
Controls **how many rounds** of dialectic reasoning Honcho performs per query.
|
||||
|
||||
| Key | Default | Range | Description |
|
||||
|-----|---------|-------|-------------|
|
||||
| `dialecticDepth` | `1` | 1-3 | Number of dialectic reasoning rounds per query |
|
||||
| `dialecticDepthLevels` | -- | array | Optional per-depth-round level overrides (see below) |
|
||||
|
||||
`dialecticDepth: 2` means Honcho runs two rounds of dialectic synthesis. The first round produces an initial answer; the second refines it.
|
||||
|
||||
`dialecticDepthLevels` lets you set the reasoning level for each round independently:
|
||||
|
||||
```json
|
||||
{
|
||||
"dialecticDepth": 3,
|
||||
"dialecticDepthLevels": ["low", "medium", "high"]
|
||||
}
|
||||
```
|
||||
|
||||
If `dialecticDepthLevels` is omitted, rounds use **proportional levels** derived from `dialecticReasoningLevel` (the base):
|
||||
|
||||
| Depth | Pass levels |
|
||||
|-------|-------------|
|
||||
| 1 | [base] |
|
||||
| 2 | [minimal, base] |
|
||||
| 3 | [minimal, base, low] |
|
||||
|
||||
This keeps earlier passes cheap while using full depth on the final synthesis.
|
||||
|
||||
**Depth at session start.** The session-start prewarm runs the full configured `dialecticDepth` in the background before turn 1. A single-pass prewarm on a cold peer often returns thin output — multi-pass depth runs the audit/reconcile cycle before the user ever speaks. Turn 1 consumes the prewarm result directly; if prewarm hasn't landed in time, turn 1 falls back to a synchronous call with a bounded timeout.
|
||||
|
||||
### Level (how hard)
|
||||
|
||||
Controls the **intensity** of each dialectic reasoning round.
|
||||
|
||||
| Key | Default | Description |
|
||||
|-----|---------|-------------|
|
||||
| `dialecticReasoningLevel` | `low` | `minimal`, `low`, `medium`, `high`, `max` |
|
||||
| `dialecticDynamic` | `true` | When `true`, the model can pass `reasoning_level` to `honcho_reasoning` to override the default per-call. `false` = always use `dialecticReasoningLevel`, model overrides ignored |
|
||||
|
||||
Higher levels produce richer synthesis but cost more tokens on Honcho's backend.
|
||||
|
||||
## Multi-Profile Setup
|
||||
|
||||
Each Hermes profile gets its own Honcho AI peer while sharing the same workspace (user context). This means:
|
||||
|
||||
- All profiles see the same user representation
|
||||
- Each profile builds its own AI identity and observations
|
||||
- Conclusions written by one profile are visible to others via the shared workspace
|
||||
|
||||
### Create a profile with Honcho peer
|
||||
|
||||
```bash
|
||||
hermes profile create coder --clone
|
||||
# creates host block hermes.coder, AI peer "coder", inherits config from default
|
||||
```
|
||||
|
||||
What `--clone` does for Honcho:
|
||||
1. Creates a `hermes.coder` host block in `honcho.json`
|
||||
2. Sets `aiPeer: "coder"` (the profile name)
|
||||
3. Inherits `workspace`, `peerName`, `writeFrequency`, `recallMode`, etc. from default
|
||||
4. Eagerly creates the peer in Honcho so it exists before first message
|
||||
|
||||
### Backfill existing profiles
|
||||
|
||||
```bash
|
||||
hermes honcho sync # creates host blocks for all profiles that don't have one yet
|
||||
```
|
||||
|
||||
### Per-profile config
|
||||
|
||||
Override any setting in the host block:
|
||||
|
||||
```json
|
||||
{
|
||||
"hosts": {
|
||||
"hermes.coder": {
|
||||
"aiPeer": "coder",
|
||||
"recallMode": "tools",
|
||||
"dialecticDepth": 2,
|
||||
"observation": {
|
||||
"user": { "observeMe": true, "observeOthers": false },
|
||||
"ai": { "observeMe": true, "observeOthers": true }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Tools
|
||||
|
||||
The agent has 5 bidirectional Honcho tools (hidden in `context` recall mode):
|
||||
|
||||
| Tool | LLM call? | Cost | Use when |
|
||||
|------|-----------|------|----------|
|
||||
| `honcho_profile` | No | minimal | Quick factual snapshot at conversation start or for fast name/role/pref lookups |
|
||||
| `honcho_search` | No | low | Fetch specific past facts to reason over yourself — raw excerpts, no synthesis |
|
||||
| `honcho_context` | No | low | Full session context snapshot: summary, representation, card, recent messages |
|
||||
| `honcho_reasoning` | Yes | medium–high | Natural language question synthesized by Honcho's dialectic engine |
|
||||
| `honcho_conclude` | No | minimal | Write or delete a persistent fact; pass `peer: "ai"` for AI self-knowledge |
|
||||
|
||||
### `honcho_profile`
|
||||
Read or update a peer card — curated key facts (name, role, preferences, communication style). Pass `card: [...]` to update; omit to read. No LLM call.
|
||||
|
||||
### `honcho_search`
|
||||
Semantic search over stored context for a specific peer. Returns raw excerpts ranked by relevance, no synthesis. Default 800 tokens, max 2000. Good when you need specific past facts to reason over yourself rather than a synthesized answer.
|
||||
|
||||
### `honcho_context`
|
||||
Full session context snapshot from Honcho — session summary, peer representation, peer card, and recent messages. No LLM call. Use when you want to see everything Honcho knows about the current session and peer in one shot.
|
||||
|
||||
### `honcho_reasoning`
|
||||
Natural language question answered by Honcho's dialectic reasoning engine (LLM call on Honcho's backend). Higher cost, higher quality. Pass `reasoning_level` to control depth: `minimal` (fast/cheap) → `low` → `medium` → `high` → `max` (thorough). Omit to use the configured default (`low`). Use for synthesized understanding of the user's patterns, goals, or current state.
|
||||
|
||||
### `honcho_conclude`
|
||||
Write or delete a persistent conclusion about a peer. Pass `conclusion: "..."` to create. Pass `delete_id: "..."` to remove a conclusion (for PII removal — Honcho self-heals incorrect conclusions over time, so deletion is only needed for PII). You MUST pass exactly one of the two.
|
||||
|
||||
### Bidirectional peer targeting
|
||||
|
||||
All 5 tools accept an optional `peer` parameter:
|
||||
- `peer: "user"` (default) — operates on the user peer
|
||||
- `peer: "ai"` — operates on this profile's AI peer
|
||||
- `peer: "<explicit-id>"` — any peer ID in the workspace
|
||||
|
||||
Examples:
|
||||
```
|
||||
honcho_profile # read user's card
|
||||
honcho_profile peer="ai" # read AI peer's card
|
||||
honcho_reasoning query="What does this user care about most?"
|
||||
honcho_reasoning query="What are my interaction patterns?" peer="ai" reasoning_level="medium"
|
||||
honcho_conclude conclusion="Prefers terse answers"
|
||||
honcho_conclude conclusion="I tend to over-explain code" peer="ai"
|
||||
honcho_conclude delete_id="abc123" # PII removal
|
||||
```
|
||||
|
||||
## Agent Usage Patterns
|
||||
|
||||
Guidelines for Hermes when Honcho memory is active.
|
||||
|
||||
### On conversation start
|
||||
|
||||
```
|
||||
1. honcho_profile → fast warmup, no LLM cost
|
||||
2. If context looks thin → honcho_context (full snapshot, still no LLM)
|
||||
3. If deep synthesis needed → honcho_reasoning (LLM call, use sparingly)
|
||||
```
|
||||
|
||||
Do NOT call `honcho_reasoning` on every turn. Auto-injection already handles ongoing context refresh. Use the reasoning tool only when you genuinely need synthesized insight the base context doesn't provide.
|
||||
|
||||
### When the user shares something to remember
|
||||
|
||||
```
|
||||
honcho_conclude conclusion="<specific, actionable fact>"
|
||||
```
|
||||
|
||||
Good conclusions: "Prefers code examples over prose explanations", "Working on a Rust async project through April 2026"
|
||||
Bad conclusions: "User said something about Rust" (too vague), "User seems technical" (already in representation)
|
||||
|
||||
### When the user asks about past context / you need to recall specifics
|
||||
|
||||
```
|
||||
honcho_search query="<topic>" → fast, no LLM, good for specific facts
|
||||
honcho_context → full snapshot with summary + messages
|
||||
honcho_reasoning query="<question>" → synthesized answer, use when search isn't enough
|
||||
```
|
||||
|
||||
### When to use `peer: "ai"`
|
||||
|
||||
Use AI peer targeting to build and query the agent's own self-knowledge:
|
||||
- `honcho_conclude conclusion="I tend to be verbose when explaining architecture" peer="ai"` — self-correction
|
||||
- `honcho_reasoning query="How do I typically handle ambiguous requests?" peer="ai"` — self-audit
|
||||
- `honcho_profile peer="ai"` — review own identity card
|
||||
|
||||
### When NOT to call tools
|
||||
|
||||
In `hybrid` and `context` modes, base context (user representation + card + session summary) is auto-injected before every turn. Do not re-fetch what was already injected. Call tools only when:
|
||||
- You need something the injected context doesn't have
|
||||
- The user explicitly asks you to recall or check memory
|
||||
- You're writing a conclusion about something new
|
||||
|
||||
### Cadence awareness
|
||||
|
||||
`honcho_reasoning` on the tool side shares the same cost as auto-injection dialectic. After an explicit tool call, the auto-injection cadence resets — avoiding double-charging the same turn.
|
||||
|
||||
## Config Reference
|
||||
|
||||
Config file: `$HERMES_HOME/honcho.json` (profile-local) or `~/.honcho/config.json` (global).
|
||||
|
||||
### Key settings
|
||||
|
||||
| Key | Default | Description |
|
||||
|-----|---------|-------------|
|
||||
| `apiKey` | -- | API key ([get one](https://app.honcho.dev)) |
|
||||
| `baseUrl` | -- | Base URL for self-hosted Honcho |
|
||||
| `peerName` | -- | User peer identity |
|
||||
| `aiPeer` | host key | AI peer identity |
|
||||
| `workspace` | host key | Shared workspace ID |
|
||||
| `recallMode` | `hybrid` | `hybrid`, `context`, or `tools` |
|
||||
| `observation` | all on | Per-peer `observeMe`/`observeOthers` booleans |
|
||||
| `writeFrequency` | `async` | `async`, `turn`, `session`, or integer N |
|
||||
| `sessionStrategy` | `per-directory` | `per-directory`, `per-repo`, `per-session`, `global` |
|
||||
| `messageMaxChars` | `25000` | Max chars per message (chunked if exceeded) |
|
||||
|
||||
### Dialectic settings
|
||||
|
||||
| Key | Default | Description |
|
||||
|-----|---------|-------------|
|
||||
| `dialecticReasoningLevel` | `low` | `minimal`, `low`, `medium`, `high`, `max` |
|
||||
| `dialecticDynamic` | `true` | Auto-bump reasoning by query complexity. `false` = fixed level |
|
||||
| `dialecticDepth` | `1` | Number of dialectic rounds per query (1-3) |
|
||||
| `dialecticDepthLevels` | -- | Optional array of per-round levels, e.g. `["low", "high"]` |
|
||||
| `dialecticMaxInputChars` | `10000` | Max chars for dialectic query input |
|
||||
|
||||
### Context budget and injection
|
||||
|
||||
| Key | Default | Description |
|
||||
|-----|---------|-------------|
|
||||
| `contextTokens` | uncapped | Max tokens for the combined base context injection (summary + representation + card). Opt-in cap — omit to leave uncapped, set to an integer to bound injection size. |
|
||||
| `injectionFrequency` | `every-turn` | `every-turn` or `first-turn` |
|
||||
| `contextCadence` | `1` | Min turns between context API calls |
|
||||
| `dialecticCadence` | `2` | Min turns between dialectic LLM calls (recommended 1–5) |
|
||||
|
||||
The `contextTokens` budget is enforced at injection time. If the session summary + representation + card exceed the budget, Honcho trims the summary first, then the representation, preserving the card. This prevents context blowup in long sessions.
|
||||
|
||||
### Memory-context sanitization
|
||||
|
||||
Honcho sanitizes the `memory-context` block before injection to prevent prompt injection and malformed content:
|
||||
|
||||
- Strips XML/HTML tags from user-authored conclusions
|
||||
- Normalizes whitespace and control characters
|
||||
- Truncates individual conclusions that exceed `messageMaxChars`
|
||||
- Escapes delimiter sequences that could break the system prompt structure
|
||||
|
||||
This fix addresses edge cases where raw user conclusions containing markup or special characters could corrupt the injected context block.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Honcho not configured"
|
||||
Run `hermes honcho setup`. Ensure `memory.provider: honcho` is in `~/.hermes/config.yaml`.
|
||||
|
||||
### Memory not persisting across sessions
|
||||
Check `hermes honcho status` -- verify `saveMessages: true` and `writeFrequency` isn't `session` (which only writes on exit).
|
||||
|
||||
### Profile not getting its own peer
|
||||
Use `--clone` when creating: `hermes profile create <name> --clone`. For existing profiles: `hermes honcho sync`.
|
||||
|
||||
### Observation changes in dashboard not reflected
|
||||
Observation config is synced from the server on each session init. Start a new session after changing settings in the Honcho UI.
|
||||
|
||||
### Messages truncated
|
||||
Messages over `messageMaxChars` (default 25k) are automatically chunked with `[continued]` markers. If you're hitting this often, check if tool results or skill content is inflating message size.
|
||||
|
||||
### Context injection too large
|
||||
If you see warnings about context budget exceeded, lower `contextTokens` or reduce `dialecticDepth`. The session summary is trimmed first when the budget is tight.
|
||||
|
||||
### Session summary missing
|
||||
Session summary requires at least one prior turn in the current Honcho session. On cold start (new session, no history), the summary is omitted and Honcho uses the cold-start prompt strategy instead.
|
||||
|
||||
## CLI Commands
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `hermes honcho setup` | Interactive setup wizard (cloud/local, identity, observation, recall, sessions) |
|
||||
| `hermes honcho status` | Show resolved config, connection test, peer info for active profile |
|
||||
| `hermes honcho enable` | Enable Honcho for the active profile (creates host block if needed) |
|
||||
| `hermes honcho disable` | Disable Honcho for the active profile |
|
||||
| `hermes honcho peer` | Show or update peer names (`--user <name>`, `--ai <name>`, `--reasoning <level>`) |
|
||||
| `hermes honcho peers` | Show peer identities across all profiles |
|
||||
| `hermes honcho mode` | Show or set recall mode (`hybrid`, `context`, `tools`) |
|
||||
| `hermes honcho tokens` | Show or set token budgets (`--context <N>`, `--dialectic <N>`) |
|
||||
| `hermes honcho sessions` | List known directory-to-session-name mappings |
|
||||
| `hermes honcho map <name>` | Map current working directory to a Honcho session name |
|
||||
| `hermes honcho identity` | Seed AI peer identity or show both peer representations |
|
||||
| `hermes honcho sync` | Create host blocks for all Hermes profiles that don't have one yet |
|
||||
| `hermes honcho migrate` | Step-by-step migration guide from OpenClaw native memory to Hermes + Honcho |
|
||||
| `hermes memory setup` | Generic memory provider picker (selecting "honcho" runs the same wizard) |
|
||||
| `hermes memory status` | Show active memory provider and config |
|
||||
| `hermes memory off` | Disable external memory provider |
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
---
|
||||
title: "Openhands — Delegate coding to OpenHands CLI (model-agnostic, LiteLLM)"
|
||||
sidebar_label: "Openhands"
|
||||
description: "Delegate coding to OpenHands CLI (model-agnostic, LiteLLM)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Openhands
|
||||
|
||||
Delegate coding to OpenHands CLI (model-agnostic, LiteLLM).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/autonomous-ai-agents/openhands` |
|
||||
| Path | `optional-skills/autonomous-ai-agents\openhands` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | Tim Koepsel (xzessmedia), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Coding-Agent`, `OpenHands`, `Model-Agnostic`, `LiteLLM` |
|
||||
| Related skills | [`claude-code`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-claude-code), [`codex`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-codex), [`opencode`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-opencode), [`hermes-agent`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# OpenHands CLI
|
||||
|
||||
Delegate coding tasks to the [OpenHands CLI](https://github.com/All-Hands-AI/OpenHands) via the `terminal` tool. OpenHands is model-agnostic: any LiteLLM-supported provider (OpenAI, Anthropic, OpenRouter, DeepSeek, Ollama, vLLM, etc.).
|
||||
|
||||
This skill is the headless-mode wrapper for batch / one-shot delegation. The interactive textual UI is not used from Hermes.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User wants a coding task delegated to OpenHands specifically.
|
||||
- User wants a coding agent that can run on a non-Anthropic / non-OpenAI provider (DeepSeek, Qwen, Ollama, vLLM, Nous, etc.) — sibling skills `claude-code` and `codex` are tied to one vendor.
|
||||
- Multi-step file edits + shell commands inside a workspace.
|
||||
|
||||
For Claude-native, prefer `claude-code`. For OpenAI-native, prefer `codex`. For Hermes-native subagents, use `delegate_task`.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. Install upstream (requires Python 3.12+ and `uv`):
|
||||
|
||||
```
|
||||
terminal(command="uv tool install openhands --python 3.12")
|
||||
```
|
||||
|
||||
Verify: `openhands --version` (currently `OpenHands CLI 1.16.0` / `SDK v1.21.0` at time of writing).
|
||||
|
||||
2. Pick a model and set env vars for `--override-with-envs`:
|
||||
|
||||
```
|
||||
export LLM_MODEL=openrouter/openai/gpt-4o-mini # or any LiteLLM slug
|
||||
export LLM_API_KEY=$OPENROUTER_API_KEY
|
||||
export LLM_BASE_URL=https://openrouter.ai/api/v1 # omit for native OpenAI
|
||||
```
|
||||
|
||||
`LLM_MODEL` uses LiteLLM's full slug. When the provider is OpenRouter the slug is doubly-prefixed: `openrouter/<vendor>/<model>` (e.g. `openrouter/anthropic/claude-sonnet-4.5`). For native Anthropic: `anthropic/claude-sonnet-4-5`. For native OpenAI: `openai/gpt-4o-mini`.
|
||||
|
||||
3. Suppress the startup banner so JSON output isn't preceded by ASCII art:
|
||||
|
||||
```
|
||||
export OPENHANDS_SUPPRESS_BANNER=1
|
||||
```
|
||||
|
||||
## How to Run
|
||||
|
||||
Always invoke through the `terminal` tool. Always pass `--headless --json --override-with-envs --exit-without-confirmation` for automation.
|
||||
|
||||
### One-shot task
|
||||
|
||||
```
|
||||
terminal(
|
||||
command="OPENHANDS_SUPPRESS_BANNER=1 LLM_MODEL=openrouter/openai/gpt-4o-mini LLM_API_KEY=$OPENROUTER_API_KEY LLM_BASE_URL=https://openrouter.ai/api/v1 openhands --headless --json --override-with-envs --exit-without-confirmation -t 'Add error handling to all API calls in src/'",
|
||||
workdir="/path/to/project",
|
||||
timeout=600
|
||||
)
|
||||
```
|
||||
|
||||
### Background for long tasks
|
||||
|
||||
```
|
||||
terminal(command="<same as above>", workdir="/path/to/project", background=true, notify_on_complete=true)
|
||||
process(action="poll", session_id="<id>")
|
||||
process(action="log", session_id="<id>")
|
||||
```
|
||||
|
||||
### Resume a previous conversation
|
||||
|
||||
OpenHands prints `Conversation ID: <32-hex>` and a `Hint: openhands --resume <dashed-uuid>` line at the end of each run. Use the dashed form to resume:
|
||||
|
||||
```
|
||||
terminal(
|
||||
command="OPENHANDS_SUPPRESS_BANNER=1 LLM_MODEL=... openhands --headless --json --override-with-envs --exit-without-confirmation --resume <dashed-uuid> -t 'Now fix the bug you found'",
|
||||
workdir="/path/to/project"
|
||||
)
|
||||
```
|
||||
|
||||
## Real Flag List
|
||||
|
||||
Verified against `openhands --help` (CLI 1.16.0). Anything not in this table is not a flag — pass it via env var or settings file.
|
||||
|
||||
| Flag | Effect |
|
||||
|------|--------|
|
||||
| `--headless` | No UI, requires `-t` or `-f`. Auto-approves all actions (no `--llm-approve` in this mode). |
|
||||
| `--json` | JSONL event stream (requires `--headless`). |
|
||||
| `-t TEXT` | Task prompt. |
|
||||
| `-f PATH` | Read task from file. |
|
||||
| `--resume [ID]` | Resume conversation. No ID → list recent. |
|
||||
| `--last` | Resume most recent (with `--resume`). |
|
||||
| `--override-with-envs` | Apply `LLM_API_KEY` / `LLM_BASE_URL` / `LLM_MODEL` env vars. Without this, OpenHands uses `~/.openhands/settings.json` and ignores the env. |
|
||||
| `--exit-without-confirmation` | Don't show the "are you sure" exit dialog. |
|
||||
| `--always-approve` / `--yolo` | Auto-approve every action (default in `--headless`). |
|
||||
| `--llm-approve` | LLM-based security gate (interactive only — does NOT work in headless). |
|
||||
| `--version` / `-v` | Print version and exit. |
|
||||
|
||||
**There is no `--model`, `--max-iterations`, `--workspace`, `--sandbox`, `--sandbox-type` flag.** Model is `LLM_MODEL`. Workspace is the `workdir` you pass to the `terminal` tool. Sandbox / runtime is the `RUNTIME` and `SANDBOX_VOLUMES` env vars.
|
||||
|
||||
## JSON Event Schema
|
||||
|
||||
With `--json --headless`, OpenHands emits JSONL — one JSON object per line, plus a handful of non-JSON status lines (`Initializing agent...`, `Agent is working`, `Agent finished`, the final summary box, `Goodbye!`, `Conversation ID:`, `Hint:`). Filter for lines starting with `{`.
|
||||
|
||||
Top-level `kind` field discriminates events:
|
||||
|
||||
- `MessageEvent` — user / agent text turn. `source` is `user` or `agent`.
|
||||
- `ActionEvent` — agent picked a tool. Read `tool_name` (`file_editor`, `terminal`, `finish`) and `action.kind` (`FileEditorAction`, `TerminalAction`, `FinishAction`).
|
||||
- `ObservationEvent` — tool result. `observation.is_error` is the success flag. `source` is `environment`.
|
||||
- `FinishAction` inside an `ActionEvent` carries the agent's final message in `action.message`.
|
||||
|
||||
The cli prints all stderr from LiteLLM/Authlib first — see Pitfalls. Parse only stdout, line by line, ignoring lines that don't start with `{`.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **LiteLLM warnings on every invocation.** The CLI prints `bedrock-runtime` and `sagemaker-runtime` warnings to stderr because `botocore` isn't installed. Plus an Authlib deprecation. These are noise, not failures. Pipe stderr to `/dev/null` or filter it out before showing the user.
|
||||
- **Banner spam.** Without `OPENHANDS_SUPPRESS_BANNER=1`, every run starts with a multi-line `+--+` ASCII box advertising the SDK. Always export it.
|
||||
- **`--override-with-envs` is mandatory for automation.** Without it, OpenHands ignores `LLM_API_KEY` / `LLM_BASE_URL` / `LLM_MODEL` and falls back to `~/.openhands/settings.json`. On a fresh install this file doesn't exist and the CLI hangs waiting for first-run setup.
|
||||
- **Model slug is LiteLLM's, not the provider's.** `openrouter/openai/gpt-4o-mini` works; `openai/gpt-4o-mini` while pointed at OpenRouter does not. `anthropic/claude-sonnet-4-5` (hyphen) is native Anthropic; `openrouter/anthropic/claude-sonnet-4.5` (dot) is via OpenRouter. Get it wrong → cryptic LiteLLM 400.
|
||||
- **`pip install openhands-ai` is the wrong package.** That's the legacy V0 SDK. The new CLI is `uv tool install openhands --python 3.12`. There is no maintained conda package.
|
||||
- **Resume ID format is fiddly.** The CLI ends with `Conversation ID: f46573d9cfdb45e492ca189bde40019b` (no dashes) and then a `Hint: openhands --resume f46573d9-cfdb-45e4-92ca-189bde40019b` (with dashes). Use the dashed form.
|
||||
- **Headless ignores `--llm-approve`.** If you pass it, you get an argparse error. Headless mode hardcodes always-approve.
|
||||
- **No Windows support upstream.** The OpenHands docs require WSL on Windows. This skill is gated `[linux, macos]` accordingly.
|
||||
- **`~/.openhands/conversations/<id>/` accumulates.** Each run persists a trajectory. Clean it up if running batches.
|
||||
- **Heavy install (~200 packages).** Use `uv tool install` (isolated venv) to avoid dependency conflicts with the active project.
|
||||
|
||||
## Verification
|
||||
|
||||
```
|
||||
terminal(
|
||||
command="OPENHANDS_SUPPRESS_BANNER=1 LLM_MODEL=openrouter/openai/gpt-4o-mini LLM_API_KEY=$OPENROUTER_API_KEY LLM_BASE_URL=https://openrouter.ai/api/v1 openhands --headless --json --override-with-envs --exit-without-confirmation -t 'Print the string OPENHANDS_OK to stdout via the terminal tool.'",
|
||||
workdir="/tmp",
|
||||
timeout=120
|
||||
)
|
||||
```
|
||||
|
||||
If the JSONL stream ends with a `FinishAction` whose `action.message` mentions `OPENHANDS_OK`, the install is working.
|
||||
|
||||
## Related
|
||||
|
||||
- [OpenHands GitHub](https://github.com/All-Hands-AI/OpenHands)
|
||||
- [OpenHands CLI command reference](https://docs.openhands.dev/openhands/usage/cli/command-reference)
|
||||
- Sibling skills: `claude-code` (Anthropic-only), `codex` (OpenAI-only), `opencode` (multi-provider via OpenCode), `hermes-agent` (Hermes subagents via `delegate_task`).
|
||||
@@ -0,0 +1,227 @@
|
||||
---
|
||||
title: "Evm — Read-only EVM client: wallets, tokens, gas across 8 chains"
|
||||
sidebar_label: "Evm"
|
||||
description: "Read-only EVM client: wallets, tokens, gas across 8 chains"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Evm
|
||||
|
||||
Read-only EVM client: wallets, tokens, gas across 8 chains.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/blockchain/evm` |
|
||||
| Path | `optional-skills/blockchain\evm` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Mibayy (@Mibayy), youssefea (@youssefea), ethernet8023 (@ethernet8023), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `EVM`, `Ethereum`, `BNB`, `BSC`, `Base`, `Arbitrum`, `Polygon`, `Optimism`, `Avalanche`, `zkSync`, `Blockchain`, `Crypto`, `Web3`, `DeFi`, `NFT`, `ENS`, `Whale`, `Security` |
|
||||
| Related skills | [`solana`](/docs/user-guide/skills/optional/blockchain/blockchain-solana) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# EVM Blockchain Skill
|
||||
|
||||
Query EVM-compatible blockchain data across 8 chains with USD pricing.
|
||||
14 commands: wallet portfolio, token info, transactions, activity, gas tracker,
|
||||
network stats, price lookup, multi-chain scan, whale detection, ENS resolution,
|
||||
allowance checker, contract inspector, and transaction decoder.
|
||||
|
||||
Supports 8 chains: Ethereum, BNB Chain (BSC), Base, Arbitrum One, Polygon,
|
||||
Optimism, Avalanche (C-Chain), zkSync Era.
|
||||
|
||||
No API key needed. Zero external dependencies — Python standard library only
|
||||
(urllib, json, argparse, threading).
|
||||
|
||||
> **Supersedes the standalone `base` skill.** Base-specific tokens (AERO, DEGEN,
|
||||
> TOSHI, BRETT, WELL, cbETH, cbBTC, wstETH, rETH) and all Base RPC functionality
|
||||
> previously living under `optional-skills/blockchain/base/` have been folded
|
||||
> into this skill. Pass `--chain base` to any command for Base coverage.
|
||||
|
||||
---
|
||||
|
||||
## When to Use
|
||||
- User asks for a wallet balance or portfolio on any EVM chain
|
||||
- User wants to check the same wallet across ALL chains at once
|
||||
- User wants to inspect a transaction by hash (or decode what it did)
|
||||
- User wants ERC-20 token metadata, price, supply, or market cap
|
||||
- User wants recent transaction history for an address
|
||||
- User wants current gas prices or to compare fees across chains
|
||||
- User wants to find large whale transfers in recent blocks
|
||||
- User asks to resolve an ENS name (vitalik.eth) or reverse-lookup an address
|
||||
- User wants to check if a contract has dangerous token approvals
|
||||
- User wants to inspect a smart contract (proxy? ERC-20? ERC-721? bytecode size?)
|
||||
- User wants to compare gas costs across chains before a transaction
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
Python 3.8+ standard library only. No pip installs required.
|
||||
Pricing: CoinGecko free API (rate-limited, ~10-30 req/min).
|
||||
ENS: ensideas.com public API.
|
||||
Tx decoding: 4byte.directory public API.
|
||||
|
||||
Override RPC endpoint: `export EVM_RPC_URL=https://your-rpc.com`
|
||||
|
||||
Helper script path: `~/.hermes/skills/blockchain/evm/scripts/evm_client.py`
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```
|
||||
SCRIPT=~/.hermes/skills/blockchain/evm/scripts/evm_client.py
|
||||
|
||||
# Network & prices
|
||||
python $SCRIPT stats # Ethereum stats
|
||||
python $SCRIPT stats --chain arbitrum # Arbitrum stats
|
||||
python $SCRIPT compare # Gas + prices ALL 8 chains
|
||||
|
||||
# Wallet
|
||||
python $SCRIPT wallet 0xd8dA...96045 # Portfolio (ETH + ERC-20)
|
||||
python $SCRIPT wallet 0xd8dA...96045 --chain bsc
|
||||
python $SCRIPT multichain 0xd8dA...96045 # Same wallet on ALL chains
|
||||
|
||||
# Tokens & prices
|
||||
python $SCRIPT price ETH
|
||||
python $SCRIPT price 0xdAC1...1ec7 # By contract address
|
||||
python $SCRIPT token 0xdAC1...1ec7 # ERC-20 metadata + market cap
|
||||
|
||||
# Transactions
|
||||
python $SCRIPT tx 0x5c50...f060 # Transaction details
|
||||
python $SCRIPT decode 0x5c50...f060 # Decode input data (4byte.directory)
|
||||
python $SCRIPT activity 0xd8dA...96045 # Recent transactions
|
||||
|
||||
# Gas
|
||||
python $SCRIPT gas # Gas prices + cost estimates
|
||||
python $SCRIPT gas --chain optimism
|
||||
|
||||
# Security
|
||||
python $SCRIPT allowance 0xd8dA...96045 # Dangerous ERC-20 approvals
|
||||
python $SCRIPT contract 0xdAC1...1ec7 # Contract inspection (proxy? standards?)
|
||||
|
||||
# ENS
|
||||
python $SCRIPT ens vitalik.eth # Name -> address + profile
|
||||
python $SCRIPT ens 0xd8dA...96045 # Address -> ENS name
|
||||
|
||||
# Whale detection
|
||||
python $SCRIPT whale # Large transfers (last 20 blocks, >$10k)
|
||||
python $SCRIPT whale --blocks 50 --min-usd 100000 --chain arbitrum
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Procedure
|
||||
|
||||
### 0. Setup Check
|
||||
```bash
|
||||
python --version # 3.8+ required
|
||||
python ~/.hermes/skills/blockchain/evm/scripts/evm_client.py stats
|
||||
```
|
||||
|
||||
### 1. Wallet Portfolio
|
||||
Native balance + known ERC-20 tokens, sorted by USD value.
|
||||
```bash
|
||||
python $SCRIPT wallet 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045
|
||||
python $SCRIPT wallet 0xd8dA... --chain bsc --no-prices # faster
|
||||
```
|
||||
|
||||
### 2. Multi-Chain Scan
|
||||
Scans all 8 chains simultaneously for the same address using threads.
|
||||
```bash
|
||||
python $SCRIPT multichain 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045
|
||||
```
|
||||
Output: per-chain native balance + token holdings + grand total USD.
|
||||
|
||||
### 3. Compare (Gas + Prices)
|
||||
All 8 chains queried in parallel. Shows cheapest/most expensive chain.
|
||||
```bash
|
||||
python $SCRIPT compare
|
||||
```
|
||||
|
||||
### 4. Transaction Details & Decode
|
||||
```bash
|
||||
python $SCRIPT tx 0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060
|
||||
python $SCRIPT decode 0x5c504ed... # Shows human-readable function signature
|
||||
```
|
||||
Decode uses 4byte.directory to translate 0xa9059cbb -> transfer(address,uint256).
|
||||
|
||||
### 5. ENS Resolution
|
||||
```bash
|
||||
python $SCRIPT ens vitalik.eth # -> 0xd8dA... + avatar + social links
|
||||
python $SCRIPT ens 0xd8dA...96045 # -> vitalik.eth
|
||||
```
|
||||
|
||||
### 6. Allowance Checker (Security)
|
||||
Checks ERC-20 approvals granted to known DEX/bridge contracts.
|
||||
```bash
|
||||
python $SCRIPT allowance 0xYourWallet
|
||||
```
|
||||
Flags UNLIMITED approvals as HIGH risk.
|
||||
|
||||
### 7. Contract Inspector
|
||||
```bash
|
||||
python $SCRIPT contract 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 # USDC (proxy)
|
||||
python $SCRIPT contract 0xdAC17F958D2ee523a2206206994597C13D831ec7 # USDT (ERC-20)
|
||||
```
|
||||
Detects: proxy (EIP-1967/EIP-1167), ERC-20, ERC-721, ERC-165. Shows bytecode size and implementation address for proxies.
|
||||
|
||||
### 8. Whale Detection
|
||||
```bash
|
||||
python $SCRIPT whale # ETH, last 20 blocks, >$10k
|
||||
python $SCRIPT whale --blocks 50 --min-usd 50000 --chain bsc
|
||||
```
|
||||
|
||||
### 9. Gas Tracker
|
||||
```bash
|
||||
python $SCRIPT gas
|
||||
python $SCRIPT gas --chain polygon
|
||||
```
|
||||
Shows gwei price + USD cost for: transfer, ERC-20 transfer, approve, swap, NFT mint, NFT transfer.
|
||||
|
||||
---
|
||||
|
||||
## Supported Chains
|
||||
| Key | Name | Native | Chain ID |
|
||||
|-----------|----------------|--------|----------|
|
||||
| ethereum | Ethereum | ETH | 1 |
|
||||
| bsc | BNB Chain | BNB | 56 |
|
||||
| base | Base | ETH | 8453 |
|
||||
| arbitrum | Arbitrum One | ETH | 42161 |
|
||||
| polygon | Polygon | POL | 137 |
|
||||
| optimism | Optimism | ETH | 10 |
|
||||
| avalanche | Avalanche C | AVAX | 43114 |
|
||||
| zksync | zkSync Era | ETH | 324 |
|
||||
|
||||
---
|
||||
|
||||
## Pitfalls
|
||||
- CoinGecko free tier: ~10-30 req/min. Use `--no-prices` for faster wallet scans.
|
||||
- Public RPCs may throttle. Set EVM_RPC_URL to a private endpoint for production.
|
||||
- `wallet` and `allowance` only check known token list (~30 tokens per chain). Use a block explorer for complete token discovery.
|
||||
- `activity` scans recent blocks only (max 200). For full history, use Etherscan API.
|
||||
- `multichain` runs 8 parallel threads — can trigger rate limits on public RPCs.
|
||||
- ENS resolution depends on a single public endpoint (ensideas.com / ens.vitalik.ca) with no fallback. If that endpoint is down, `ens` will fail — re-run later or use a block explorer.
|
||||
- Tx decoding depends on a single public endpoint (4byte.directory) with no fallback. Selectors not in their database show up as `unknown`.
|
||||
- **L2 gas estimates are L2-execution only.** On rollups like Base, Arbitrum, Optimism, and zkSync, the actual transaction cost also includes an L1 data-posting fee that depends on calldata size and current L1 gas prices. The `gas` command does not estimate that L1 component. For Base specifically, see the network's L1 fee oracle (contract `0x420000000000000000000000000000000000000F`).
|
||||
- Address / tx-hash inputs are validated for 0x-prefix + correct length + hex, but EIP-55 checksum casing is **not** enforced (RPC endpoints accept any-case hex).
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
```bash
|
||||
# Should print current block, gas price, ETH price
|
||||
python ~/.hermes/skills/blockchain/evm/scripts/evm_client.py stats
|
||||
|
||||
# Should resolve vitalik.eth to 0xd8dA...
|
||||
python ~/.hermes/skills/blockchain/evm/scripts/evm_client.py ens vitalik.eth
|
||||
```
|
||||
@@ -0,0 +1,228 @@
|
||||
---
|
||||
title: "Hyperliquid — Hyperliquid market data, account history, trade review"
|
||||
sidebar_label: "Hyperliquid"
|
||||
description: "Hyperliquid market data, account history, trade review"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Hyperliquid
|
||||
|
||||
Hyperliquid market data, account history, trade review.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/blockchain/hyperliquid` |
|
||||
| Path | `optional-skills/blockchain\hyperliquid` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | Hugo Sequier (Hugo-SEQUIER), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Hyperliquid`, `Blockchain`, `Crypto`, `Trading`, `Perpetuals`, `Spot`, `DeFi` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Hyperliquid Skill
|
||||
|
||||
Query Hyperliquid market and account data through the public `/info` endpoint.
|
||||
Read-only — no API key, no signing, no order placement.
|
||||
|
||||
12 commands: `dexs`, `markets`, `spots`, `candles`, `funding`, `l2`, `state`,
|
||||
`spot-balances`, `fills`, `orders`, `review`, `export`. Stdlib only
|
||||
(`urllib`, `json`, `argparse`).
|
||||
|
||||
---
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks for Hyperliquid perp or spot market data, candles, funding, or L2 book
|
||||
- User wants to inspect a wallet's perp positions, spot balances, fills, or orders
|
||||
- User wants a post-trade review combining recent fills with market context
|
||||
- User wants to inspect builder-deployed perp dexs or HIP-3 markets
|
||||
- User wants a normalized JSON export of candles + funding for backtesting prep
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Stdlib only — no external packages, no API key.
|
||||
|
||||
The script reads `${HERMES_HOME:-~/.hermes}/.env` for two optional defaults:
|
||||
|
||||
- `HYPERLIQUID_API_URL` — defaults to `https://api.hyperliquid.xyz`. Set to
|
||||
`https://api.hyperliquid-testnet.xyz` for testnet.
|
||||
- `HYPERLIQUID_USER_ADDRESS` — default address for `state`, `spot-balances`,
|
||||
`fills`, `orders`, and `review`. If unset, pass the address as the first
|
||||
positional argument.
|
||||
|
||||
A project `.env` in the current working directory is honored as a dev fallback.
|
||||
|
||||
Helper script: `~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py`
|
||||
|
||||
---
|
||||
|
||||
## How to Run
|
||||
|
||||
Invoke through the `terminal` tool:
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py <command> [args]
|
||||
```
|
||||
|
||||
Add `--json` to any command for machine-readable output.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
hyperliquid_client.py dexs
|
||||
hyperliquid_client.py markets [--dex DEX] [--limit N] [--sort volume|oi|funding_abs|change_abs|name]
|
||||
hyperliquid_client.py spots [--limit N]
|
||||
hyperliquid_client.py candles <coin> [--interval 1h] [--hours 24] [--limit N]
|
||||
hyperliquid_client.py funding <coin> [--hours 72] [--limit N]
|
||||
hyperliquid_client.py l2 <coin> [--levels N]
|
||||
hyperliquid_client.py state [address] [--dex DEX]
|
||||
hyperliquid_client.py spot-balances [address] [--limit N]
|
||||
hyperliquid_client.py fills [address] [--hours N] [--limit N] [--aggregate-by-time]
|
||||
hyperliquid_client.py orders [address] [--limit N]
|
||||
hyperliquid_client.py review [address] [--coin COIN] [--hours N] [--fills N]
|
||||
hyperliquid_client.py export <coin> [--interval 1h] [--hours N] [--output PATH]
|
||||
```
|
||||
|
||||
For `state`, `spot-balances`, `fills`, `orders`, and `review`, the address is
|
||||
optional when `HYPERLIQUID_USER_ADDRESS` is set in `${HERMES_HOME:-~/.hermes}/.env`.
|
||||
|
||||
---
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Discover DEXs and Markets
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py dexs
|
||||
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
markets --limit 15 --sort volume
|
||||
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
spots --limit 15
|
||||
```
|
||||
|
||||
- `--dex` only applies to perp endpoints; omit for the first perp dex.
|
||||
- Spot pairs may show as `PURR/USDC` or aliases like `@107`.
|
||||
- HIP-3 markets prefix the coin with the dex, e.g. `mydex:BTC`.
|
||||
|
||||
### 2. Pull Historical Market Data
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
candles BTC --interval 1h --hours 72 --limit 48
|
||||
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
funding BTC --hours 168 --limit 30
|
||||
```
|
||||
|
||||
Time-range endpoints paginate. For larger windows, repeat with a later
|
||||
`startTime` or use `export` (below).
|
||||
|
||||
### 3. Inspect Live Order Book
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
l2 BTC --levels 10
|
||||
```
|
||||
|
||||
Use when asked about book depth, near-term liquidity, or potential market
|
||||
impact of a large order.
|
||||
|
||||
### 4. Review an Account
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
state 0xabc...
|
||||
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
spot-balances
|
||||
```
|
||||
|
||||
`state` returns perp positions; `spot-balances` returns spot inventory.
|
||||
Use these for "how are my positions?", "what am I holding?", "how much is
|
||||
withdrawable?".
|
||||
|
||||
### 5. Review Fills and Orders
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
fills 0xabc... --hours 72 --limit 25
|
||||
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
orders --limit 25
|
||||
```
|
||||
|
||||
### 6. Generate a Trade Review
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
review 0xabc... --hours 72 --fills 50
|
||||
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
review --coin BTC --hours 168
|
||||
```
|
||||
|
||||
Reports realized PnL, fees, win/loss counts, coin breakdowns, market trend
|
||||
and average funding for each traded perp, plus heuristics (fee drag,
|
||||
concentration, counter-trend losses).
|
||||
|
||||
For deeper post-trade analysis: start with `review` to find problem coins
|
||||
or windows → pull `fills` and `orders` for that period → pull `candles`
|
||||
and `funding` for each traded coin → judge decision quality separately
|
||||
from outcome quality.
|
||||
|
||||
### 7. Export a Reusable Dataset
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
export BTC --interval 1h --hours 168 --output ./btc-1h-7d.json
|
||||
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
export BTC --interval 15m --hours 72 --end-time-ms 1760000000000
|
||||
```
|
||||
|
||||
Output JSON contains: schema version, source metadata, exact time window,
|
||||
normalized candle rows, normalized funding rows, summary stats. Use
|
||||
`--end-time-ms` for reproducible windows.
|
||||
|
||||
---
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Public info endpoints are rate-limited. Large historical queries may
|
||||
return capped windows; iterate with later `startTime` values.
|
||||
- `fills --hours ...` uses `userFillsByTime`, which only exposes a
|
||||
recent rolling window — not full archive history.
|
||||
- `historicalOrders` returns recent orders only; not a full export.
|
||||
- The `review` command is heuristic. It cannot reconstruct intent,
|
||||
order placement quality, or true slippage from fills alone.
|
||||
- The `export` command writes a normalized dataset, not a backtest
|
||||
engine. You still need your own slippage/fill model.
|
||||
- Spot aliases like `@107` are valid identifiers even when the UI shows
|
||||
a friendlier name.
|
||||
- `l2` is a point-in-time snapshot, not a time series.
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/hyperliquid/scripts/hyperliquid_client.py \
|
||||
markets --limit 5
|
||||
```
|
||||
|
||||
Should print the top Hyperliquid perp markets by 24h notional volume.
|
||||
@@ -0,0 +1,225 @@
|
||||
---
|
||||
title: "Solana — Query Solana wallets, tokens, txs, and NFTs in USD"
|
||||
sidebar_label: "Solana"
|
||||
description: "Query Solana wallets, tokens, txs, and NFTs in USD"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Solana
|
||||
|
||||
Query Solana wallets, tokens, txs, and NFTs in USD.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/blockchain/solana` |
|
||||
| Path | `optional-skills/blockchain\solana` |
|
||||
| Version | `0.2.0` |
|
||||
| Author | Deniz Alagoz (gizdusum), enhanced by Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Solana`, `Blockchain`, `Crypto`, `Web3`, `RPC`, `DeFi`, `NFT` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Solana Blockchain Skill
|
||||
|
||||
Query Solana on-chain data enriched with USD pricing via CoinGecko.
|
||||
8 commands: wallet portfolio, token info, transactions, activity, NFTs,
|
||||
whale detection, network stats, and price lookup.
|
||||
|
||||
No API key needed. Uses only Python standard library (urllib, json, argparse).
|
||||
|
||||
---
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks for a Solana wallet balance, token holdings, or portfolio value
|
||||
- User wants to inspect a specific transaction by signature
|
||||
- User wants SPL token metadata, price, supply, or top holders
|
||||
- User wants recent transaction history for an address
|
||||
- User wants NFTs owned by a wallet
|
||||
- User wants to find large SOL transfers (whale detection)
|
||||
- User wants Solana network health, TPS, epoch, or SOL price
|
||||
- User asks "what's the price of BONK/JUP/SOL?"
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
The helper script uses only Python standard library (urllib, json, argparse).
|
||||
No external packages required.
|
||||
|
||||
Pricing data comes from CoinGecko's free API (no key needed, rate-limited
|
||||
to ~10-30 requests/minute). For faster lookups, use `--no-prices` flag.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
RPC endpoint (default): https://api.mainnet-beta.solana.com
|
||||
Override: export SOLANA_RPC_URL=https://your-private-rpc.com
|
||||
|
||||
Helper script path: ~/.hermes/skills/blockchain/solana/scripts/solana_client.py
|
||||
|
||||
```
|
||||
python solana_client.py wallet <address> [--limit N] [--all] [--no-prices]
|
||||
python solana_client.py tx <signature>
|
||||
python solana_client.py token <mint_address>
|
||||
python solana_client.py activity <address> [--limit N]
|
||||
python solana_client.py nft <address>
|
||||
python solana_client.py whales [--min-sol N]
|
||||
python solana_client.py stats
|
||||
python solana_client.py price <mint_or_symbol>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Procedure
|
||||
|
||||
### 0. Setup Check
|
||||
|
||||
```bash
|
||||
python --version
|
||||
|
||||
# Optional: set a private RPC for better rate limits
|
||||
export SOLANA_RPC_URL="https://api.mainnet-beta.solana.com"
|
||||
|
||||
# Confirm connectivity
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py stats
|
||||
```
|
||||
|
||||
### 1. Wallet Portfolio
|
||||
|
||||
Get SOL balance, SPL token holdings with USD values, NFT count, and
|
||||
portfolio total. Tokens sorted by value, dust filtered, known tokens
|
||||
labeled by name (BONK, JUP, USDC, etc.).
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py \
|
||||
wallet 9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM
|
||||
```
|
||||
|
||||
Flags:
|
||||
- `--limit N` — show top N tokens (default: 20)
|
||||
- `--all` — show all tokens, no dust filter, no limit
|
||||
- `--no-prices` — skip CoinGecko price lookups (faster, RPC-only)
|
||||
|
||||
Output includes: SOL balance + USD value, token list with prices sorted
|
||||
by value, dust count, NFT summary, total portfolio value in USD.
|
||||
|
||||
### 2. Transaction Details
|
||||
|
||||
Inspect a full transaction by its base58 signature. Shows balance changes
|
||||
in both SOL and USD.
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py \
|
||||
tx 5j7s8K...your_signature_here
|
||||
```
|
||||
|
||||
Output: slot, timestamp, fee, status, balance changes (SOL + USD),
|
||||
program invocations.
|
||||
|
||||
### 3. Token Info
|
||||
|
||||
Get SPL token metadata, current price, market cap, supply, decimals,
|
||||
mint/freeze authorities, and top 5 holders.
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py \
|
||||
token DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263
|
||||
```
|
||||
|
||||
Output: name, symbol, decimals, supply, price, market cap, top 5
|
||||
holders with percentages.
|
||||
|
||||
### 4. Recent Activity
|
||||
|
||||
List recent transactions for an address (default: last 10, max: 25).
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py \
|
||||
activity 9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM --limit 25
|
||||
```
|
||||
|
||||
### 5. NFT Portfolio
|
||||
|
||||
List NFTs owned by a wallet (heuristic: SPL tokens with amount=1, decimals=0).
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py \
|
||||
nft 9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM
|
||||
```
|
||||
|
||||
Note: Compressed NFTs (cNFTs) are not detected by this heuristic.
|
||||
|
||||
### 6. Whale Detector
|
||||
|
||||
Scan the most recent block for large SOL transfers with USD values.
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py \
|
||||
whales --min-sol 500
|
||||
```
|
||||
|
||||
Note: scans the latest block only — point-in-time snapshot, not historical.
|
||||
|
||||
### 7. Network Stats
|
||||
|
||||
Live Solana network health: current slot, epoch, TPS, supply, validator
|
||||
version, SOL price, and market cap.
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py stats
|
||||
```
|
||||
|
||||
### 8. Price Lookup
|
||||
|
||||
Quick price check for any token by mint address or known symbol.
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py price BONK
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py price JUP
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py price SOL
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py price DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263
|
||||
```
|
||||
|
||||
Known symbols: SOL, USDC, USDT, BONK, JUP, WETH, JTO, mSOL, stSOL,
|
||||
PYTH, HNT, RNDR, WEN, W, TNSR, DRIFT, bSOL, JLP, WIF, MEW, BOME, PENGU.
|
||||
|
||||
---
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **CoinGecko rate-limits** — free tier allows ~10-30 requests/minute.
|
||||
Price lookups use 1 request per token. Wallets with many tokens may
|
||||
not get prices for all of them. Use `--no-prices` for speed.
|
||||
- **Public RPC rate-limits** — Solana mainnet public RPC limits requests.
|
||||
For production use, set SOLANA_RPC_URL to a private endpoint
|
||||
(Helius, QuickNode, Triton).
|
||||
- **NFT detection is heuristic** — amount=1 + decimals=0. Compressed
|
||||
NFTs (cNFTs) and Token-2022 NFTs won't appear.
|
||||
- **Whale detector scans latest block only** — not historical. Results
|
||||
vary by the moment you query.
|
||||
- **Transaction history** — public RPC keeps ~2 days. Older transactions
|
||||
may not be available.
|
||||
- **Token names** — ~25 well-known tokens are labeled by name. Others
|
||||
show abbreviated mint addresses. Use the `token` command for full info.
|
||||
- **Retry on 429** — both RPC and CoinGecko calls retry up to 2 times
|
||||
with exponential backoff on rate-limit errors.
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
# Should print current Solana slot, TPS, and SOL price
|
||||
python ~/.hermes/skills/blockchain/solana/scripts/solana_client.py stats
|
||||
```
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
---
|
||||
title: "One Three One Rule — 1-3-1 decision briefs: problem, three options, one pick"
|
||||
sidebar_label: "One Three One Rule"
|
||||
description: "1-3-1 decision briefs: problem, three options, one pick"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# One Three One Rule
|
||||
|
||||
1-3-1 decision briefs: problem, three options, one pick.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/communication/one-three-one-rule` |
|
||||
| Path | `optional-skills/communication\one-three-one-rule` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Willard Moore |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `communication`, `decision-making`, `proposals`, `trade-offs` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# 1-3-1 Communication Rule
|
||||
|
||||
Structured decision-making format for when a task has multiple viable approaches and the user needs a clear recommendation. Produces a concise problem framing, three options with trade-offs, and an actionable plan for the recommended path.
|
||||
|
||||
## When to Use
|
||||
|
||||
- The user explicitly asks for a "1-3-1" response.
|
||||
- The user says "give me options" or "what are my choices" for a technical decision.
|
||||
- A task has multiple viable approaches with meaningful trade-offs (architecture, tooling, migration strategy).
|
||||
- The user needs a proposal they can forward to a team or stakeholder.
|
||||
|
||||
Do NOT use for simple questions with one obvious answer, debugging sessions, or tasks where the user has already decided on an approach.
|
||||
|
||||
## Procedure
|
||||
|
||||
1. **Problem** (one sentence)
|
||||
- State the core decision or desired outcome in a single concise sentence.
|
||||
- Focus on the *what*, not the *how* — no implementation details, tool names, or specific technologies.
|
||||
- Keep it tight. If you need "and", you're describing two problems.
|
||||
|
||||
2. **Options** (exactly three)
|
||||
- Present three distinct, viable approaches labeled A, B, C.
|
||||
- Each option gets a brief description, pros, and cons.
|
||||
- Options should represent genuinely different strategies, not minor variations of the same approach.
|
||||
|
||||
3. **Recommendation** (one option)
|
||||
- State which option you recommend and why, based on the user's context and priorities.
|
||||
- Be direct — this is your professional judgment, not a hedge.
|
||||
|
||||
4. **Definition of Done**
|
||||
- List the specific success criteria for the recommended option.
|
||||
- These are concrete, verifiable outcomes — not vague aspirations.
|
||||
- If the user picks a different option, revise this section to match.
|
||||
|
||||
5. **Implementation Plan**
|
||||
- Concrete steps to execute the recommended option.
|
||||
- Include specific commands, tools, or actions where applicable.
|
||||
- If the user picks a different option, revise this section to match.
|
||||
|
||||
## Verification
|
||||
|
||||
- Response has exactly one Problem sentence.
|
||||
- Response has exactly three Options (A, B, C) with pros and cons for each.
|
||||
- Response has a single Recommendation that picks one option with reasoning.
|
||||
- Definition of Done and Implementation Plan align with the recommended option.
|
||||
- If the user selects a different option, Recommendation, DoD, and Implementation Plan update accordingly.
|
||||
|
||||
## Example
|
||||
|
||||
User: "Give me a 1-3-1 for adding retry logic to our API client."
|
||||
|
||||
Agent:
|
||||
|
||||
**Problem:** API calls to external services fail intermittently under load and need graceful retry handling.
|
||||
|
||||
**Options:**
|
||||
|
||||
- **Option A: Exponential backoff with jitter in a shared utility.**
|
||||
Pros: Simple, well-understood pattern; single implementation shared across all callers.
|
||||
Cons: No circuit-breaking; callers still block during retries.
|
||||
|
||||
- **Option B: Retry library (tenacity) as a decorator on each endpoint call.**
|
||||
Pros: Configurable per-endpoint; built-in support for circuit breakers and rate limits.
|
||||
Cons: Adds a dependency; decorator pattern can obscure control flow.
|
||||
|
||||
- **Option C: Queue-based async retry with dead letter handling.**
|
||||
Pros: Non-blocking; failed calls are tracked and replayable; scales well.
|
||||
Cons: Significant complexity increase; requires a queue backend; overkill for low-volume services.
|
||||
|
||||
**Recommendation:** Option A. The call volume doesn't justify queue infrastructure, and a shared utility with exponential backoff + jitter covers the failure mode cleanly without new dependencies.
|
||||
|
||||
**Definition of Done:**
|
||||
- `api_retry()` utility handles transient HTTP errors (429, 502, 503, 504).
|
||||
- Retries up to 3 times with exponential backoff and jitter.
|
||||
- All external API calls route through the retry utility.
|
||||
- Logs each retry attempt with endpoint and attempt number.
|
||||
- Tests cover retry exhaustion, immediate success, and transient-then-success scenarios.
|
||||
|
||||
**Implementation Plan:**
|
||||
1. Create `utils/api_retry.py` with configurable max retries, base delay, and retryable status codes.
|
||||
2. Add jitter using `random.uniform(0, base_delay)` to prevent thundering herd.
|
||||
3. Wrap existing API calls in `api_client.py` with the retry utility.
|
||||
4. Add unit tests mocking HTTP responses for each retry scenario.
|
||||
5. Verify under load with a simple stress test against a flaky endpoint mock.
|
||||
@@ -0,0 +1,338 @@
|
||||
---
|
||||
title: "Ascii Art — ASCII art: pyfiglet, cowsay, boxes, image-to-ascii"
|
||||
sidebar_label: "Ascii Art"
|
||||
description: "ASCII art: pyfiglet, cowsay, boxes, image-to-ascii"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Ascii Art
|
||||
|
||||
ASCII art: pyfiglet, cowsay, boxes, image-to-ascii.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/ascii-art` |
|
||||
| Path | `optional-skills/creative\ascii-art` |
|
||||
| Version | `4.0.0` |
|
||||
| Author | 0xbyt4, Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `ASCII`, `Art`, `Banners`, `Creative`, `Unicode`, `Text-Art`, `pyfiglet`, `figlet`, `cowsay`, `boxes` |
|
||||
| Related skills | [`excalidraw`](/docs/user-guide/skills/optional/creative/creative-excalidraw) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# ASCII Art Skill
|
||||
|
||||
Multiple tools for different ASCII art needs. All tools are local CLI programs or free REST APIs — no API keys required.
|
||||
|
||||
## Tool 1: Text Banners (pyfiglet — local)
|
||||
|
||||
Render text as large ASCII art banners. 571 built-in fonts.
|
||||
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
pip install pyfiglet --break-system-packages -q
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
python -m pyfiglet "YOUR TEXT" -f slant
|
||||
python -m pyfiglet "TEXT" -f doom -w 80 # Set width
|
||||
python -m pyfiglet --list_fonts # List all 571 fonts
|
||||
```
|
||||
|
||||
### Recommended fonts
|
||||
|
||||
| Style | Font | Best for |
|
||||
|-------|------|----------|
|
||||
| Clean & modern | `slant` | Project names, headers |
|
||||
| Bold & blocky | `doom` | Titles, logos |
|
||||
| Big & readable | `big` | Banners |
|
||||
| Classic banner | `banner3` | Wide displays |
|
||||
| Compact | `small` | Subtitles |
|
||||
| Cyberpunk | `cyberlarge` | Tech themes |
|
||||
| 3D effect | `3-d` | Splash screens |
|
||||
| Gothic | `gothic` | Dramatic text |
|
||||
|
||||
### Tips
|
||||
|
||||
- Preview 2-3 fonts and let the user pick their favorite
|
||||
- Short text (1-8 chars) works best with detailed fonts like `doom` or `block`
|
||||
- Long text works better with compact fonts like `small` or `mini`
|
||||
|
||||
## Tool 2: Text Banners (asciified API — remote, no install)
|
||||
|
||||
Free REST API that converts text to ASCII art. 250+ FIGlet fonts. Returns plain text directly — no parsing needed. Use this when pyfiglet is not installed or as a quick alternative.
|
||||
|
||||
### Usage (via terminal curl)
|
||||
|
||||
```bash
|
||||
# Basic text banner (default font)
|
||||
curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello+World"
|
||||
|
||||
# With a specific font
|
||||
curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=Slant"
|
||||
curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=Doom"
|
||||
curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=Star+Wars"
|
||||
curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=3-D"
|
||||
curl -s "https://asciified.thelicato.io/api/v2/ascii?text=Hello&font=Banner3"
|
||||
|
||||
# List all available fonts (returns JSON array)
|
||||
curl -s "https://asciified.thelicato.io/api/v2/fonts"
|
||||
```
|
||||
|
||||
### Tips
|
||||
|
||||
- URL-encode spaces as `+` in the text parameter
|
||||
- The response is plain text ASCII art — no JSON wrapping, ready to display
|
||||
- Font names are case-sensitive; use the fonts endpoint to get exact names
|
||||
- Works from any terminal with curl — no Python or pip needed
|
||||
|
||||
## Tool 3: Cowsay (Message Art)
|
||||
|
||||
Classic tool that wraps text in a speech bubble with an ASCII character.
|
||||
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
sudo apt install cowsay -y # Debian/Ubuntu
|
||||
# brew install cowsay # macOS
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
cowsay "Hello World"
|
||||
cowsay -f tux "Linux rules" # Tux the penguin
|
||||
cowsay -f dragon "Rawr!" # Dragon
|
||||
cowsay -f stegosaurus "Roar!" # Stegosaurus
|
||||
cowthink "Hmm..." # Thought bubble
|
||||
cowsay -l # List all characters
|
||||
```
|
||||
|
||||
### Available characters (50+)
|
||||
|
||||
`beavis.zen`, `bong`, `bunny`, `cheese`, `daemon`, `default`, `dragon`,
|
||||
`dragon-and-cow`, `elephant`, `eyes`, `flaming-skull`, `ghostbusters`,
|
||||
`hellokitty`, `kiss`, `kitty`, `koala`, `luke-koala`, `mech-and-cow`,
|
||||
`meow`, `moofasa`, `moose`, `ren`, `sheep`, `skeleton`, `small`,
|
||||
`stegosaurus`, `stimpy`, `supermilker`, `surgery`, `three-eyes`,
|
||||
`turkey`, `turtle`, `tux`, `udder`, `vader`, `vader-koala`, `www`
|
||||
|
||||
### Eye/tongue modifiers
|
||||
|
||||
```bash
|
||||
cowsay -b "Borg" # =_= eyes
|
||||
cowsay -d "Dead" # x_x eyes
|
||||
cowsay -g "Greedy" # $_$ eyes
|
||||
cowsay -p "Paranoid" # @_@ eyes
|
||||
cowsay -s "Stoned" # *_* eyes
|
||||
cowsay -w "Wired" # O_O eyes
|
||||
cowsay -e "OO" "Msg" # Custom eyes
|
||||
cowsay -T "U " "Msg" # Custom tongue
|
||||
```
|
||||
|
||||
## Tool 4: Boxes (Decorative Borders)
|
||||
|
||||
Draw decorative ASCII art borders/frames around any text. 70+ built-in designs.
|
||||
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
sudo apt install boxes -y # Debian/Ubuntu
|
||||
# brew install boxes # macOS
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
echo "Hello World" | boxes # Default box
|
||||
echo "Hello World" | boxes -d stone # Stone border
|
||||
echo "Hello World" | boxes -d parchment # Parchment scroll
|
||||
echo "Hello World" | boxes -d cat # Cat border
|
||||
echo "Hello World" | boxes -d dog # Dog border
|
||||
echo "Hello World" | boxes -d unicornsay # Unicorn
|
||||
echo "Hello World" | boxes -d diamonds # Diamond pattern
|
||||
echo "Hello World" | boxes -d c-cmt # C-style comment
|
||||
echo "Hello World" | boxes -d html-cmt # HTML comment
|
||||
echo "Hello World" | boxes -a c # Center text
|
||||
boxes -l # List all 70+ designs
|
||||
```
|
||||
|
||||
### Combine with pyfiglet or asciified
|
||||
|
||||
```bash
|
||||
python -m pyfiglet "HERMES" -f slant | boxes -d stone
|
||||
# Or without pyfiglet installed:
|
||||
curl -s "https://asciified.thelicato.io/api/v2/ascii?text=HERMES&font=Slant" | boxes -d stone
|
||||
```
|
||||
|
||||
## Tool 5: TOIlet (Colored Text Art)
|
||||
|
||||
Like pyfiglet but with ANSI color effects and visual filters. Great for terminal eye candy.
|
||||
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
sudo apt install toilet toilet-fonts -y # Debian/Ubuntu
|
||||
# brew install toilet # macOS
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
toilet "Hello World" # Basic text art
|
||||
toilet -f bigmono12 "Hello" # Specific font
|
||||
toilet --gay "Rainbow!" # Rainbow coloring
|
||||
toilet --metal "Metal!" # Metallic effect
|
||||
toilet -F border "Bordered" # Add border
|
||||
toilet -F border --gay "Fancy!" # Combined effects
|
||||
toilet -f pagga "Block" # Block-style font (unique to toilet)
|
||||
toilet -F list # List available filters
|
||||
```
|
||||
|
||||
### Filters
|
||||
|
||||
`crop`, `gay` (rainbow), `metal`, `flip`, `flop`, `180`, `left`, `right`, `border`
|
||||
|
||||
**Note**: toilet outputs ANSI escape codes for colors — works in terminals but may not render in all contexts (e.g., plain text files, some chat platforms).
|
||||
|
||||
## Tool 6: Image to ASCII Art
|
||||
|
||||
Convert images (PNG, JPEG, GIF, WEBP) to ASCII art.
|
||||
|
||||
### Option A: ascii-image-converter (recommended, modern)
|
||||
|
||||
```bash
|
||||
# Install
|
||||
sudo snap install ascii-image-converter
|
||||
# OR: go install github.com/TheZoraiz/ascii-image-converter@latest
|
||||
```
|
||||
|
||||
```bash
|
||||
ascii-image-converter image.png # Basic
|
||||
ascii-image-converter image.png -C # Color output
|
||||
ascii-image-converter image.png -d 60,30 # Set dimensions
|
||||
ascii-image-converter image.png -b # Braille characters
|
||||
ascii-image-converter image.png -n # Negative/inverted
|
||||
ascii-image-converter https://url/image.jpg # Direct URL
|
||||
ascii-image-converter image.png --save-txt out # Save as text
|
||||
```
|
||||
|
||||
### Option B: jp2a (lightweight, JPEG only)
|
||||
|
||||
```bash
|
||||
sudo apt install jp2a -y
|
||||
jp2a --width=80 image.jpg
|
||||
jp2a --colors image.jpg # Colorized
|
||||
```
|
||||
|
||||
## Tool 7: Search Pre-Made ASCII Art
|
||||
|
||||
Search curated ASCII art from the web. Use `terminal` with `curl`.
|
||||
|
||||
### Source A: ascii.co.uk (recommended for pre-made art)
|
||||
|
||||
Large collection of classic ASCII art organized by subject. Art is inside HTML `<pre>` tags. Fetch the page with curl, then extract art with a small Python snippet.
|
||||
|
||||
**URL pattern:** `https://ascii.co.uk/art/{subject}`
|
||||
|
||||
**Step 1 — Fetch the page:**
|
||||
|
||||
```bash
|
||||
curl -s 'https://ascii.co.uk/art/cat' -o /tmp/ascii_art.html
|
||||
```
|
||||
|
||||
**Step 2 — Extract art from pre tags:**
|
||||
|
||||
```python
|
||||
import re, html
|
||||
with open('/tmp/ascii_art.html') as f:
|
||||
text = f.read()
|
||||
arts = re.findall(r'<pre[^>]*>(.*?)</pre>', text, re.DOTALL)
|
||||
for art in arts:
|
||||
clean = re.sub(r'<[^>]+>', '', art)
|
||||
clean = html.unescape(clean).strip()
|
||||
if len(clean) > 30:
|
||||
print(clean)
|
||||
print('\n---\n')
|
||||
```
|
||||
|
||||
**Available subjects** (use as URL path):
|
||||
- Animals: `cat`, `dog`, `horse`, `bird`, `fish`, `dragon`, `snake`, `rabbit`, `elephant`, `dolphin`, `butterfly`, `owl`, `wolf`, `bear`, `penguin`, `turtle`
|
||||
- Objects: `car`, `ship`, `airplane`, `rocket`, `guitar`, `computer`, `coffee`, `beer`, `cake`, `house`, `castle`, `sword`, `crown`, `key`
|
||||
- Nature: `tree`, `flower`, `sun`, `moon`, `star`, `mountain`, `ocean`, `rainbow`
|
||||
- Characters: `skull`, `robot`, `angel`, `wizard`, `pirate`, `ninja`, `alien`
|
||||
- Holidays: `christmas`, `halloween`, `valentine`
|
||||
|
||||
**Tips:**
|
||||
- Preserve artist signatures/initials — important etiquette
|
||||
- Multiple art pieces per page — pick the best one for the user
|
||||
- Works reliably via curl, no JavaScript needed
|
||||
|
||||
### Source B: GitHub Octocat API (fun easter egg)
|
||||
|
||||
Returns a random GitHub Octocat with a wise quote. No auth needed.
|
||||
|
||||
```bash
|
||||
curl -s https://api.github.com/octocat
|
||||
```
|
||||
|
||||
## Tool 8: Fun ASCII Utilities (via curl)
|
||||
|
||||
These free services return ASCII art directly — great for fun extras.
|
||||
|
||||
### QR Codes as ASCII Art
|
||||
|
||||
```bash
|
||||
curl -s "qrenco.de/Hello+World"
|
||||
curl -s "qrenco.de/https://example.com"
|
||||
```
|
||||
|
||||
### Weather as ASCII Art
|
||||
|
||||
```bash
|
||||
curl -s "wttr.in/London" # Full weather report with ASCII graphics
|
||||
curl -s "wttr.in/Moon" # Moon phase in ASCII art
|
||||
curl -s "v2.wttr.in/London" # Detailed version
|
||||
```
|
||||
|
||||
## Tool 9: LLM-Generated Custom Art (Fallback)
|
||||
|
||||
When tools above don't have what's needed, generate ASCII art directly using these Unicode characters:
|
||||
|
||||
### Character Palette
|
||||
|
||||
**Box Drawing:** `╔ ╗ ╚ ╝ ║ ═ ╠ ╣ ╦ ╩ ╬ ┌ ┐ └ ┘ │ ─ ├ ┤ ┬ ┴ ┼ ╭ ╮ ╰ ╯`
|
||||
|
||||
**Block Elements:** `░ ▒ ▓ █ ▄ ▀ ▌ ▐ ▖ ▗ ▘ ▝ ▚ ▞`
|
||||
|
||||
**Geometric & Symbols:** `◆ ◇ ◈ ● ○ ◉ ■ □ ▲ △ ▼ ▽ ★ ☆ ✦ ✧ ◀ ▶ ◁ ▷ ⬡ ⬢ ⌂`
|
||||
|
||||
### Rules
|
||||
|
||||
- Max width: 60 characters per line (terminal-safe)
|
||||
- Max height: 15 lines for banners, 25 for scenes
|
||||
- Monospace only: output must render correctly in fixed-width fonts
|
||||
|
||||
## Decision Flow
|
||||
|
||||
1. **Text as a banner** → pyfiglet if installed, otherwise asciified API via curl
|
||||
2. **Wrap a message in fun character art** → cowsay
|
||||
3. **Add decorative border/frame** → boxes (can combine with pyfiglet/asciified)
|
||||
4. **Art of a specific thing** (cat, rocket, dragon) → ascii.co.uk via curl + parsing
|
||||
5. **Convert an image to ASCII** → ascii-image-converter or jp2a
|
||||
6. **QR code** → qrenco.de via curl
|
||||
7. **Weather/moon art** → wttr.in via curl
|
||||
8. **Something custom/creative** → LLM generation with Unicode palette
|
||||
9. **Any tool not installed** → install it, or fall back to next option
|
||||
+588
@@ -0,0 +1,588 @@
|
||||
---
|
||||
title: "Audiocraft Audio Generation — AudioCraft: MusicGen text-to-music, AudioGen text-to-sound"
|
||||
sidebar_label: "Audiocraft Audio Generation"
|
||||
description: "AudioCraft: MusicGen text-to-music, AudioGen text-to-sound"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Audiocraft Audio Generation
|
||||
|
||||
AudioCraft: MusicGen text-to-music, AudioGen text-to-sound.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/audiocraft-audio-generation` |
|
||||
| Path | `optional-skills/creative\audiocraft-audio-generation` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `audiocraft`, `torch>=2.0.0`, `transformers>=4.30.0` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Multimodal`, `Audio Generation`, `Text-to-Music`, `Text-to-Audio`, `MusicGen` |
|
||||
| Related skills | [`heartmula`](/docs/user-guide/skills/optional/creative/creative-heartmula), [`songwriting-and-ai-music`](/docs/user-guide/skills/bundled/creative/creative-songwriting-and-ai-music) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# AudioCraft: Audio Generation
|
||||
|
||||
Guide to using Meta's AudioCraft for text-to-music and text-to-audio generation with MusicGen, AudioGen, and EnCodec.
|
||||
|
||||
## When to use AudioCraft
|
||||
|
||||
**Use AudioCraft when:**
|
||||
- Need to generate music from text descriptions
|
||||
- Creating sound effects and environmental audio
|
||||
- Building music generation applications
|
||||
- Need melody-conditioned music generation
|
||||
- Want stereo audio output
|
||||
- Require controllable music generation with style transfer
|
||||
|
||||
**Key features:**
|
||||
- **MusicGen**: Text-to-music generation with melody conditioning
|
||||
- **AudioGen**: Text-to-sound effects generation
|
||||
- **EnCodec**: High-fidelity neural audio codec
|
||||
- **Multiple model sizes**: Small (300M) to Large (3.3B)
|
||||
- **Stereo support**: Full stereo audio generation
|
||||
- **Style conditioning**: MusicGen-Style for reference-based generation
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **Stable Audio**: For longer commercial music generation
|
||||
- **Bark**: For text-to-speech with music/sound effects
|
||||
- **Riffusion**: For spectogram-based music generation
|
||||
- **OpenAI Jukebox**: For raw audio generation with lyrics
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# From PyPI
|
||||
pip install audiocraft
|
||||
|
||||
# From GitHub (latest)
|
||||
pip install git+https://github.com/facebookresearch/audiocraft.git
|
||||
|
||||
# Or use HuggingFace Transformers
|
||||
pip install transformers torch torchaudio
|
||||
```
|
||||
|
||||
### Basic text-to-music (AudioCraft)
|
||||
|
||||
```python
|
||||
import torchaudio
|
||||
from audiocraft.models import MusicGen
|
||||
|
||||
# Load model
|
||||
model = MusicGen.get_pretrained('facebook/musicgen-small')
|
||||
|
||||
# Set generation parameters
|
||||
model.set_generation_params(
|
||||
duration=8, # seconds
|
||||
top_k=250,
|
||||
temperature=1.0
|
||||
)
|
||||
|
||||
# Generate from text
|
||||
descriptions = ["happy upbeat electronic dance music with synths"]
|
||||
wav = model.generate(descriptions)
|
||||
|
||||
# Save audio
|
||||
torchaudio.save("output.wav", wav[0].cpu(), sample_rate=32000)
|
||||
```
|
||||
|
||||
### Using HuggingFace Transformers
|
||||
|
||||
```python
|
||||
from transformers import AutoProcessor, MusicgenForConditionalGeneration
|
||||
import scipy
|
||||
|
||||
# Load model and processor
|
||||
processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
|
||||
model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
|
||||
model.to("cuda")
|
||||
|
||||
# Generate music
|
||||
inputs = processor(
|
||||
text=["80s pop track with bassy drums and synth"],
|
||||
padding=True,
|
||||
return_tensors="pt"
|
||||
).to("cuda")
|
||||
|
||||
audio_values = model.generate(
|
||||
**inputs,
|
||||
do_sample=True,
|
||||
guidance_scale=3,
|
||||
max_new_tokens=256
|
||||
)
|
||||
|
||||
# Save
|
||||
sampling_rate = model.config.audio_encoder.sampling_rate
|
||||
scipy.io.wavfile.write("output.wav", rate=sampling_rate, data=audio_values[0, 0].cpu().numpy())
|
||||
```
|
||||
|
||||
### Text-to-sound with AudioGen
|
||||
|
||||
```python
|
||||
from audiocraft.models import AudioGen
|
||||
|
||||
# Load AudioGen
|
||||
model = AudioGen.get_pretrained('facebook/audiogen-medium')
|
||||
|
||||
model.set_generation_params(duration=5)
|
||||
|
||||
# Generate sound effects
|
||||
descriptions = ["dog barking in a park with birds chirping"]
|
||||
wav = model.generate(descriptions)
|
||||
|
||||
torchaudio.save("sound.wav", wav[0].cpu(), sample_rate=16000)
|
||||
```
|
||||
|
||||
## Core concepts
|
||||
|
||||
### Architecture overview
|
||||
|
||||
<!-- ascii-guard-ignore -->
|
||||
```
|
||||
AudioCraft Architecture:
|
||||
┌──────────────────────────────────────────────────────────────┐
|
||||
│ Text Encoder (T5) │
|
||||
│ │ │
|
||||
│ Text Embeddings │
|
||||
└────────────────────────┬─────────────────────────────────────┘
|
||||
│
|
||||
┌────────────────────────▼─────────────────────────────────────┐
|
||||
│ Transformer Decoder (LM) │
|
||||
│ Auto-regressively generates audio tokens │
|
||||
│ Using efficient token interleaving patterns │
|
||||
└────────────────────────┬─────────────────────────────────────┘
|
||||
│
|
||||
┌────────────────────────▼─────────────────────────────────────┐
|
||||
│ EnCodec Audio Decoder │
|
||||
│ Converts tokens back to audio waveform │
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
### Model variants
|
||||
|
||||
| Model | Size | Description | Use Case |
|
||||
|-------|------|-------------|----------|
|
||||
| `musicgen-small` | 300M | Text-to-music | Quick generation |
|
||||
| `musicgen-medium` | 1.5B | Text-to-music | Balanced |
|
||||
| `musicgen-large` | 3.3B | Text-to-music | Best quality |
|
||||
| `musicgen-melody` | 1.5B | Text + melody | Melody conditioning |
|
||||
| `musicgen-melody-large` | 3.3B | Text + melody | Best melody |
|
||||
| `musicgen-stereo-*` | Varies | Stereo output | Stereo generation |
|
||||
| `musicgen-style` | 1.5B | Style transfer | Reference-based |
|
||||
| `audiogen-medium` | 1.5B | Text-to-sound | Sound effects |
|
||||
|
||||
### Generation parameters
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `duration` | 8.0 | Length in seconds (1-120) |
|
||||
| `top_k` | 250 | Top-k sampling |
|
||||
| `top_p` | 0.0 | Nucleus sampling (0 = disabled) |
|
||||
| `temperature` | 1.0 | Sampling temperature |
|
||||
| `cfg_coef` | 3.0 | Classifier-free guidance |
|
||||
|
||||
## MusicGen usage
|
||||
|
||||
### Text-to-music generation
|
||||
|
||||
```python
|
||||
from audiocraft.models import MusicGen
|
||||
import torchaudio
|
||||
|
||||
model = MusicGen.get_pretrained('facebook/musicgen-medium')
|
||||
|
||||
# Configure generation
|
||||
model.set_generation_params(
|
||||
duration=30, # Up to 30 seconds
|
||||
top_k=250, # Sampling diversity
|
||||
top_p=0.0, # 0 = use top_k only
|
||||
temperature=1.0, # Creativity (higher = more varied)
|
||||
cfg_coef=3.0 # Text adherence (higher = stricter)
|
||||
)
|
||||
|
||||
# Generate multiple samples
|
||||
descriptions = [
|
||||
"epic orchestral soundtrack with strings and brass",
|
||||
"chill lo-fi hip hop beat with jazzy piano",
|
||||
"energetic rock song with electric guitar"
|
||||
]
|
||||
|
||||
# Generate (returns [batch, channels, samples])
|
||||
wav = model.generate(descriptions)
|
||||
|
||||
# Save each
|
||||
for i, audio in enumerate(wav):
|
||||
torchaudio.save(f"music_{i}.wav", audio.cpu(), sample_rate=32000)
|
||||
```
|
||||
|
||||
### Melody-conditioned generation
|
||||
|
||||
```python
|
||||
from audiocraft.models import MusicGen
|
||||
import torchaudio
|
||||
|
||||
# Load melody model
|
||||
model = MusicGen.get_pretrained('facebook/musicgen-melody')
|
||||
model.set_generation_params(duration=30)
|
||||
|
||||
# Load melody audio
|
||||
melody, sr = torchaudio.load("melody.wav")
|
||||
|
||||
# Generate with melody conditioning
|
||||
descriptions = ["acoustic guitar folk song"]
|
||||
wav = model.generate_with_chroma(descriptions, melody, sr)
|
||||
|
||||
torchaudio.save("melody_conditioned.wav", wav[0].cpu(), sample_rate=32000)
|
||||
```
|
||||
|
||||
### Stereo generation
|
||||
|
||||
```python
|
||||
from audiocraft.models import MusicGen
|
||||
|
||||
# Load stereo model
|
||||
model = MusicGen.get_pretrained('facebook/musicgen-stereo-medium')
|
||||
model.set_generation_params(duration=15)
|
||||
|
||||
descriptions = ["ambient electronic music with wide stereo panning"]
|
||||
wav = model.generate(descriptions)
|
||||
|
||||
# wav shape: [batch, 2, samples] for stereo
|
||||
print(f"Stereo shape: {wav.shape}") # [1, 2, 480000]
|
||||
torchaudio.save("stereo.wav", wav[0].cpu(), sample_rate=32000)
|
||||
```
|
||||
|
||||
### Audio continuation
|
||||
|
||||
```python
|
||||
from transformers import AutoProcessor, MusicgenForConditionalGeneration
|
||||
|
||||
processor = AutoProcessor.from_pretrained("facebook/musicgen-medium")
|
||||
model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-medium")
|
||||
|
||||
# Load audio to continue
|
||||
import torchaudio
|
||||
audio, sr = torchaudio.load("intro.wav")
|
||||
|
||||
# Process with text and audio
|
||||
inputs = processor(
|
||||
audio=audio.squeeze().numpy(),
|
||||
sampling_rate=sr,
|
||||
text=["continue with a epic chorus"],
|
||||
padding=True,
|
||||
return_tensors="pt"
|
||||
)
|
||||
|
||||
# Generate continuation
|
||||
audio_values = model.generate(**inputs, do_sample=True, guidance_scale=3, max_new_tokens=512)
|
||||
```
|
||||
|
||||
## MusicGen-Style usage
|
||||
|
||||
### Style-conditioned generation
|
||||
|
||||
```python
|
||||
from audiocraft.models import MusicGen
|
||||
|
||||
# Load style model
|
||||
model = MusicGen.get_pretrained('facebook/musicgen-style')
|
||||
|
||||
# Configure generation with style
|
||||
model.set_generation_params(
|
||||
duration=30,
|
||||
cfg_coef=3.0,
|
||||
cfg_coef_beta=5.0 # Style influence
|
||||
)
|
||||
|
||||
# Configure style conditioner
|
||||
model.set_style_conditioner_params(
|
||||
eval_q=3, # RVQ quantizers (1-6)
|
||||
excerpt_length=3.0 # Style excerpt length
|
||||
)
|
||||
|
||||
# Load style reference
|
||||
style_audio, sr = torchaudio.load("reference_style.wav")
|
||||
|
||||
# Generate with text + style
|
||||
descriptions = ["upbeat dance track"]
|
||||
wav = model.generate_with_style(descriptions, style_audio, sr)
|
||||
```
|
||||
|
||||
### Style-only generation (no text)
|
||||
|
||||
```python
|
||||
# Generate matching style without text prompt
|
||||
model.set_generation_params(
|
||||
duration=30,
|
||||
cfg_coef=3.0,
|
||||
cfg_coef_beta=None # Disable double CFG for style-only
|
||||
)
|
||||
|
||||
wav = model.generate_with_style([None], style_audio, sr)
|
||||
```
|
||||
|
||||
## AudioGen usage
|
||||
|
||||
### Sound effect generation
|
||||
|
||||
```python
|
||||
from audiocraft.models import AudioGen
|
||||
import torchaudio
|
||||
|
||||
model = AudioGen.get_pretrained('facebook/audiogen-medium')
|
||||
model.set_generation_params(duration=10)
|
||||
|
||||
# Generate various sounds
|
||||
descriptions = [
|
||||
"thunderstorm with heavy rain and lightning",
|
||||
"busy city traffic with car horns",
|
||||
"ocean waves crashing on rocks",
|
||||
"crackling campfire in forest"
|
||||
]
|
||||
|
||||
wav = model.generate(descriptions)
|
||||
|
||||
for i, audio in enumerate(wav):
|
||||
torchaudio.save(f"sound_{i}.wav", audio.cpu(), sample_rate=16000)
|
||||
```
|
||||
|
||||
## EnCodec usage
|
||||
|
||||
### Audio compression
|
||||
|
||||
```python
|
||||
from audiocraft.models import CompressionModel
|
||||
import torch
|
||||
import torchaudio
|
||||
|
||||
# Load EnCodec
|
||||
model = CompressionModel.get_pretrained('facebook/encodec_32khz')
|
||||
|
||||
# Load audio
|
||||
wav, sr = torchaudio.load("audio.wav")
|
||||
|
||||
# Ensure correct sample rate
|
||||
if sr != 32000:
|
||||
resampler = torchaudio.transforms.Resample(sr, 32000)
|
||||
wav = resampler(wav)
|
||||
|
||||
# Encode to tokens
|
||||
with torch.no_grad():
|
||||
encoded = model.encode(wav.unsqueeze(0))
|
||||
codes = encoded[0] # Audio codes
|
||||
|
||||
# Decode back to audio
|
||||
with torch.no_grad():
|
||||
decoded = model.decode(codes)
|
||||
|
||||
torchaudio.save("reconstructed.wav", decoded[0].cpu(), sample_rate=32000)
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: Music generation pipeline
|
||||
|
||||
```python
|
||||
import torch
|
||||
import torchaudio
|
||||
from audiocraft.models import MusicGen
|
||||
|
||||
class MusicGenerator:
|
||||
def __init__(self, model_name="facebook/musicgen-medium"):
|
||||
self.model = MusicGen.get_pretrained(model_name)
|
||||
self.sample_rate = 32000
|
||||
|
||||
def generate(self, prompt, duration=30, temperature=1.0, cfg=3.0):
|
||||
self.model.set_generation_params(
|
||||
duration=duration,
|
||||
top_k=250,
|
||||
temperature=temperature,
|
||||
cfg_coef=cfg
|
||||
)
|
||||
|
||||
with torch.no_grad():
|
||||
wav = self.model.generate([prompt])
|
||||
|
||||
return wav[0].cpu()
|
||||
|
||||
def generate_batch(self, prompts, duration=30):
|
||||
self.model.set_generation_params(duration=duration)
|
||||
|
||||
with torch.no_grad():
|
||||
wav = self.model.generate(prompts)
|
||||
|
||||
return wav.cpu()
|
||||
|
||||
def save(self, audio, path):
|
||||
torchaudio.save(path, audio, sample_rate=self.sample_rate)
|
||||
|
||||
# Usage
|
||||
generator = MusicGenerator()
|
||||
audio = generator.generate(
|
||||
"epic cinematic orchestral music",
|
||||
duration=30,
|
||||
temperature=1.0
|
||||
)
|
||||
generator.save(audio, "epic_music.wav")
|
||||
```
|
||||
|
||||
### Workflow 2: Sound design batch processing
|
||||
|
||||
```python
|
||||
import json
|
||||
from pathlib import Path
|
||||
from audiocraft.models import AudioGen
|
||||
import torchaudio
|
||||
|
||||
def batch_generate_sounds(sound_specs, output_dir):
|
||||
"""
|
||||
Generate multiple sounds from specifications.
|
||||
|
||||
Args:
|
||||
sound_specs: list of {"name": str, "description": str, "duration": float}
|
||||
output_dir: output directory path
|
||||
"""
|
||||
model = AudioGen.get_pretrained('facebook/audiogen-medium')
|
||||
output_dir = Path(output_dir)
|
||||
output_dir.mkdir(exist_ok=True)
|
||||
|
||||
results = []
|
||||
|
||||
for spec in sound_specs:
|
||||
model.set_generation_params(duration=spec.get("duration", 5))
|
||||
|
||||
wav = model.generate([spec["description"]])
|
||||
|
||||
output_path = output_dir / f"{spec['name']}.wav"
|
||||
torchaudio.save(str(output_path), wav[0].cpu(), sample_rate=16000)
|
||||
|
||||
results.append({
|
||||
"name": spec["name"],
|
||||
"path": str(output_path),
|
||||
"description": spec["description"]
|
||||
})
|
||||
|
||||
return results
|
||||
|
||||
# Usage
|
||||
sounds = [
|
||||
{"name": "explosion", "description": "massive explosion with debris", "duration": 3},
|
||||
{"name": "footsteps", "description": "footsteps on wooden floor", "duration": 5},
|
||||
{"name": "door", "description": "wooden door creaking and closing", "duration": 2}
|
||||
]
|
||||
|
||||
results = batch_generate_sounds(sounds, "sound_effects/")
|
||||
```
|
||||
|
||||
### Workflow 3: Gradio demo
|
||||
|
||||
```python
|
||||
import gradio as gr
|
||||
import torch
|
||||
import torchaudio
|
||||
from audiocraft.models import MusicGen
|
||||
|
||||
model = MusicGen.get_pretrained('facebook/musicgen-small')
|
||||
|
||||
def generate_music(prompt, duration, temperature, cfg_coef):
|
||||
model.set_generation_params(
|
||||
duration=duration,
|
||||
temperature=temperature,
|
||||
cfg_coef=cfg_coef
|
||||
)
|
||||
|
||||
with torch.no_grad():
|
||||
wav = model.generate([prompt])
|
||||
|
||||
# Save to temp file
|
||||
path = "temp_output.wav"
|
||||
torchaudio.save(path, wav[0].cpu(), sample_rate=32000)
|
||||
return path
|
||||
|
||||
demo = gr.Interface(
|
||||
fn=generate_music,
|
||||
inputs=[
|
||||
gr.Textbox(label="Music Description", placeholder="upbeat electronic dance music"),
|
||||
gr.Slider(1, 30, value=8, label="Duration (seconds)"),
|
||||
gr.Slider(0.5, 2.0, value=1.0, label="Temperature"),
|
||||
gr.Slider(1.0, 10.0, value=3.0, label="CFG Coefficient")
|
||||
],
|
||||
outputs=gr.Audio(label="Generated Music"),
|
||||
title="MusicGen Demo"
|
||||
)
|
||||
|
||||
demo.launch()
|
||||
```
|
||||
|
||||
## Performance optimization
|
||||
|
||||
### Memory optimization
|
||||
|
||||
```python
|
||||
# Use smaller model
|
||||
model = MusicGen.get_pretrained('facebook/musicgen-small')
|
||||
|
||||
# Clear cache between generations
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
# Generate shorter durations
|
||||
model.set_generation_params(duration=10) # Instead of 30
|
||||
|
||||
# Use half precision
|
||||
model = model.half()
|
||||
```
|
||||
|
||||
### Batch processing efficiency
|
||||
|
||||
```python
|
||||
# Process multiple prompts at once (more efficient)
|
||||
descriptions = ["prompt1", "prompt2", "prompt3", "prompt4"]
|
||||
wav = model.generate(descriptions) # Single batch
|
||||
|
||||
# Instead of
|
||||
for desc in descriptions:
|
||||
wav = model.generate([desc]) # Multiple batches (slower)
|
||||
```
|
||||
|
||||
### GPU memory requirements
|
||||
|
||||
| Model | FP32 VRAM | FP16 VRAM |
|
||||
|-------|-----------|-----------|
|
||||
| musicgen-small | ~4GB | ~2GB |
|
||||
| musicgen-medium | ~8GB | ~4GB |
|
||||
| musicgen-large | ~16GB | ~8GB |
|
||||
|
||||
## Common issues
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| CUDA OOM | Use smaller model, reduce duration |
|
||||
| Poor quality | Increase cfg_coef, better prompts |
|
||||
| Generation too short | Check max duration setting |
|
||||
| Audio artifacts | Try different temperature |
|
||||
| Stereo not working | Use stereo model variant |
|
||||
|
||||
## References
|
||||
|
||||
- **[Advanced Usage](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\audiocraft-audio-generation/references/advanced-usage.md)** - Training, fine-tuning, deployment
|
||||
- **[Troubleshooting](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\audiocraft-audio-generation/references/troubleshooting.md)** - Common issues and solutions
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/facebookresearch/audiocraft
|
||||
- **Paper (MusicGen)**: https://arxiv.org/abs/2306.05284
|
||||
- **Paper (AudioGen)**: https://arxiv.org/abs/2209.15352
|
||||
- **HuggingFace**: https://huggingface.co/facebook/musicgen-small
|
||||
- **Demo**: https://huggingface.co/spaces/facebook/MusicGen
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
---
|
||||
title: "Baoyu Article Illustrator — Article illustrations: type × style × palette consistency"
|
||||
sidebar_label: "Baoyu Article Illustrator"
|
||||
description: "Article illustrations: type × style × palette consistency"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Baoyu Article Illustrator
|
||||
|
||||
Article illustrations: type × style × palette consistency.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/baoyu-article-illustrator` |
|
||||
| Path | `optional-skills/creative\baoyu-article-illustrator` |
|
||||
| Version | `1.57.0` |
|
||||
| Author | 宝玉 (JimLiu) |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `article-illustration`, `creative`, `image-generation` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Article Illustrator
|
||||
|
||||
Adapted from [baoyu-article-illustrator](https://github.com/JimLiu/baoyu-skills) for Hermes Agent's tool ecosystem.
|
||||
|
||||
Analyze articles, identify illustration positions, generate images with **Type × Style × Palette** consistency.
|
||||
|
||||
## When to Use
|
||||
|
||||
Trigger this skill when the user asks to illustrate an article, add images to an article, generate illustrations for content, or uses phrases like "为文章配图", "illustrate article", or "add images". The user provides an article (file path or pasted content) and optionally specifies type, style, palette, or density.
|
||||
|
||||
## Three Dimensions
|
||||
|
||||
| Dimension | Controls | Examples |
|
||||
|-----------|----------|----------|
|
||||
| **Type** | Information structure | infographic, scene, flowchart, comparison, framework, timeline |
|
||||
| **Style** | Rendering approach | notion, warm, minimal, blueprint, watercolor, elegant |
|
||||
| **Palette** | Color scheme (optional) | macaron, warm, neon — overrides style's default colors |
|
||||
|
||||
Combine freely: `type=infographic, style=vector-illustration, palette=macaron`.
|
||||
|
||||
Or use presets: `edu-visual` → type + style + palette in one shot. See [style-presets.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/style-presets.md).
|
||||
|
||||
## Types
|
||||
|
||||
| Type | Best For |
|
||||
|------|----------|
|
||||
| `infographic` | Data, metrics, technical |
|
||||
| `scene` | Narratives, emotional |
|
||||
| `flowchart` | Processes, workflows |
|
||||
| `comparison` | Side-by-side, options |
|
||||
| `framework` | Models, architecture |
|
||||
| `timeline` | History, evolution |
|
||||
|
||||
## Styles
|
||||
|
||||
See [references/styles.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/styles.md) for Core Styles, the full gallery, and Type × Style compatibility.
|
||||
|
||||
## Output Structure
|
||||
|
||||
<!-- ascii-guard-ignore -->
|
||||
```
|
||||
{output-dir}/
|
||||
├── source-{slug}.{ext} # Only for pasted content
|
||||
├── outline.md
|
||||
├── prompts/
|
||||
│ └── NN-{type}-{slug}.md
|
||||
└── NN-{type}-{slug}.png
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
**Default output directory**:
|
||||
|
||||
| Input | Output Directory | Markdown Insert Path |
|
||||
|-------|------------------|----------------------|
|
||||
| Article file path | `{article-dir}/imgs/` | `imgs/NN-{type}-{slug}.png` |
|
||||
| Pasted content | `illustrations/{topic-slug}/` (cwd) | `illustrations/{topic-slug}/NN-{type}-{slug}.png` |
|
||||
|
||||
If the user asks for a different layout (e.g., images alongside the article, or a `illustrations/` subdirectory), honor that.
|
||||
|
||||
**Slug**: 2-4 words, kebab-case. **Conflict**: append `-YYYYMMDD-HHMMSS`.
|
||||
|
||||
## Core Principles
|
||||
|
||||
- **Visualize concepts, not metaphors** — if the article uses a metaphor (e.g., "电锯切西瓜"), illustrate the underlying concept, not the literal image.
|
||||
- **Labels use article data** — actual numbers, terms, and quotes from the article, not generic placeholders.
|
||||
- **Prompt files are reproducibility records** — every illustration must have a saved prompt file under `prompts/` before any image is generated.
|
||||
- **Strip secrets** — scan source content for API keys, tokens, or credentials before writing anything to disk.
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
- [ ] Step 1: Detect reference images (if provided)
|
||||
- [ ] Step 2: Analyze content
|
||||
- [ ] Step 3: Confirm settings (clarify tool, one question at a time)
|
||||
- [ ] Step 4: Generate outline
|
||||
- [ ] Step 5: Generate prompts
|
||||
- [ ] Step 6: Generate images (image_generate)
|
||||
- [ ] Step 7: Finalize
|
||||
```
|
||||
|
||||
### Step 1: Detect Reference Images
|
||||
|
||||
If the user supplies reference images (paths pasted inline, attachments, or a URL):
|
||||
|
||||
1. For each reference, call `vision_analyze` with the path/URL and a question asking for style, palette, composition, and subject. Record the returned description in `{output-dir}/references/NN-ref-{slug}.md` via `write_file`.
|
||||
2. **Do not** try to copy the binary via `write_file` / `read_file` — those are text-only. If you want a local copy for the record, use `terminal` (`cp "$src" "{output-dir}/references/NN-ref-{slug}.{ext}"`). The skill itself never needs to read the binary; it works off the vision description.
|
||||
3. Since `image_generate` doesn't take image inputs, the vision description is what gets embedded in prompts during Step 5.
|
||||
|
||||
Full procedures: [references/workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/workflow.md#step-1-detect-reference-images).
|
||||
|
||||
### Step 2: Analyze
|
||||
|
||||
| Analysis | Output |
|
||||
|----------|--------|
|
||||
| Content type | Technical / Tutorial / Methodology / Narrative |
|
||||
| Purpose | information / visualization / imagination |
|
||||
| Core arguments | 2-5 main points |
|
||||
| Positions | Where illustrations add value |
|
||||
|
||||
Read source (file path → `read_file`, or pasted text) and write the analysis to `{output-dir}/analysis.md` using `write_file`.
|
||||
|
||||
Full procedures: [references/workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/workflow.md#step-2-analyze).
|
||||
|
||||
### Step 3: Confirm Settings
|
||||
|
||||
Use the `clarify` tool. Since `clarify` handles one question at a time, ask the most important question first. Skip any question whose answer is already present in the user's request.
|
||||
|
||||
| Order | Question | Options |
|
||||
|-------|----------|---------|
|
||||
| Q1 | **Preset or Type** | [Recommended preset], [alt preset], or manual: infographic, scene, flowchart, comparison, framework, timeline, mixed |
|
||||
| Q2 | **Density** | minimal (1-2), balanced (3-5), per-section (Recommended), rich (6+) |
|
||||
| Q3 | **Style** *(skip if preset chosen in Q1)* | [Recommended], minimal-flat, sci-fi, hand-drawn, editorial, scene, poster |
|
||||
| Q4 | **Palette** *(optional)* | Default (style colors), macaron, warm, neon |
|
||||
| Q5 | **Language** *(only if article language is ambiguous)* | article language / user language |
|
||||
|
||||
Don't ask more than 2-3 `clarify` questions in a row. If the user already specified these in their request, skip entirely.
|
||||
|
||||
Full procedures: [references/workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/workflow.md#step-3-confirm-settings).
|
||||
|
||||
### Step 4: Generate Outline → `outline.md`
|
||||
|
||||
Save `{output-dir}/outline.md` using `write_file` with frontmatter (type, density, style, palette, image_count) and one entry per illustration:
|
||||
|
||||
```yaml
|
||||
## Illustration 1
|
||||
**Position**: [section/paragraph]
|
||||
**Purpose**: [why]
|
||||
**Visual Content**: [what to show]
|
||||
**Filename**: 01-infographic-concept-name.png
|
||||
```
|
||||
|
||||
Full template: [references/workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/workflow.md#step-4-generate-outline).
|
||||
|
||||
### Step 5: Generate Prompts
|
||||
|
||||
**BLOCKING**: Every illustration must have a saved prompt file before any image is generated — the prompt file is the reproducibility record.
|
||||
|
||||
For each illustration:
|
||||
|
||||
1. Create a prompt file per [references/prompt-construction.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/prompt-construction.md).
|
||||
2. Save to `{output-dir}/prompts/NN-{type}-{slug}.md` using `write_file` with YAML frontmatter.
|
||||
3. Prompts MUST use type-specific templates with structured sections (ZONES / LABELS / COLORS / STYLE / ASPECT).
|
||||
4. LABELS MUST include article-specific data: actual numbers, terms, metrics, quotes.
|
||||
5. Process references (`direct`/`style`/`palette`) per prompt frontmatter — for `direct` usage, embed a textual description of the reference in the prompt (since `image_generate` doesn't take reference-image inputs).
|
||||
|
||||
### Step 6: Generate Images
|
||||
|
||||
For each prompt file:
|
||||
|
||||
1. Call `image_generate(prompt=..., aspect_ratio=...)`. `image_generate` returns a JSON result containing an image URL; it does NOT write to disk and does NOT accept an output path.
|
||||
2. Map the prompt's `ASPECT` to `image_generate`'s enum: `16:9` → `landscape`, `9:16` → `portrait`, `1:1` → `square`. Custom ratios → nearest named aspect.
|
||||
3. Download the returned URL to `{output-dir}/NN-{type}-{slug}.png` via `terminal` (e.g. `curl -sSL -o "{output-dir}/NN-{type}-{slug}.png" "{url}"`).
|
||||
4. On generation failure, auto-retry once.
|
||||
|
||||
Note: the underlying image-generation backend is user-configured (default: FAL FLUX 2 Klein 9B) and is NOT agent-selectable via `image_generate`. Do not write model names into prompts expecting them to route.
|
||||
|
||||
### Step 7: Finalize
|
||||
|
||||
Insert `` after the corresponding paragraph. Alt text: concise description in the article's language.
|
||||
|
||||
Report:
|
||||
|
||||
```
|
||||
Article Illustration Complete!
|
||||
Article: [path] | Type: [type] | Density: [level] | Style: [style] | Palette: [palette or default]
|
||||
Images: X/N generated
|
||||
```
|
||||
|
||||
## Modification
|
||||
|
||||
| Action | Steps |
|
||||
|--------|-------|
|
||||
| Edit | Update prompt → Regenerate → Update reference |
|
||||
| Add | Position → Prompt → Generate → Update outline → Insert |
|
||||
| Delete | Delete files → Remove reference → Update outline |
|
||||
|
||||
## References
|
||||
|
||||
| File | Content |
|
||||
|------|---------|
|
||||
| [references/workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/workflow.md) | Detailed procedures |
|
||||
| [references/usage.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/usage.md) | Invocation examples |
|
||||
| [references/styles.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/styles.md) | Style gallery + Palette gallery |
|
||||
| [references/style-presets.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/style-presets.md) | Preset shortcuts (type + style + palette) |
|
||||
| [references/prompt-construction.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-article-illustrator/references/prompt-construction.md) | Prompt templates |
|
||||
|
||||
## Pitfalls
|
||||
|
||||
1. **Data integrity is paramount** — never summarize, paraphrase, or alter source statistics. "73% increase" stays "73% increase".
|
||||
2. **Strip secrets** — scan source content for API keys, tokens, or credentials before including in any output file.
|
||||
3. **Don't illustrate metaphors literally** — visualize the underlying concept.
|
||||
4. **Prompt files are mandatory** — no image generation without a saved prompt file. The file is what lets you regenerate or switch backends later.
|
||||
5. **`image_generate` aspect ratios** — the tool supports `landscape`, `portrait`, and `square`. Custom ratios map to the nearest option.
|
||||
6. **`image_generate` returns a URL, not a local file** — always download via `terminal` (`curl`) before inserting local image paths into the article.
|
||||
7. **No backend selection from the agent** — `image_generate` uses whatever model the user configured (default: FAL FLUX 2 Klein 9B). Don't write `"use <model> to generate this"` into prompts expecting it to route.
|
||||
@@ -0,0 +1,264 @@
|
||||
---
|
||||
title: "Baoyu Comic — Knowledge comics (知识漫画): educational, biography, tutorial"
|
||||
sidebar_label: "Baoyu Comic"
|
||||
description: "Knowledge comics (知识漫画): educational, biography, tutorial"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Baoyu Comic
|
||||
|
||||
Knowledge comics (知识漫画): educational, biography, tutorial.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/baoyu-comic` |
|
||||
| Path | `optional-skills/creative\baoyu-comic` |
|
||||
| Version | `1.56.1` |
|
||||
| Author | 宝玉 (JimLiu) |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `comic`, `knowledge-comic`, `creative`, `image-generation` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Knowledge Comic Creator
|
||||
|
||||
Adapted from [baoyu-comic](https://github.com/JimLiu/baoyu-skills) for Hermes Agent's tool ecosystem.
|
||||
|
||||
Create original knowledge comics with flexible art style × tone combinations.
|
||||
|
||||
## When to Use
|
||||
|
||||
Trigger this skill when the user asks to create a knowledge/educational comic, biography comic, tutorial comic, or uses terms like "知识漫画", "教育漫画", or "Logicomix-style". The user provides content (text, file path, URL, or topic) and optionally specifies art style, tone, layout, aspect ratio, or language.
|
||||
|
||||
## Reference Images
|
||||
|
||||
Hermes' `image_generate` tool is **prompt-only** — it accepts a text prompt and an aspect ratio, and returns an image URL. It does **NOT** accept reference images. When the user supplies a reference image, use it to **extract traits in text** that get embedded in every page prompt:
|
||||
|
||||
**Intake**: Accept file paths when the user provides them (or pastes images in conversation).
|
||||
- File path(s) → copy to `refs/NN-ref-{slug}.{ext}` alongside the comic output for provenance
|
||||
- Pasted image with no path → ask the user for the path via `clarify`, or extract style traits verbally as a text fallback
|
||||
- No reference → skip this section
|
||||
|
||||
**Usage modes** (per reference):
|
||||
|
||||
| Usage | Effect |
|
||||
|-------|--------|
|
||||
| `style` | Extract style traits (line treatment, texture, mood) and append to every page's prompt body |
|
||||
| `palette` | Extract hex colors and append to every page's prompt body |
|
||||
| `scene` | Extract scene composition or subject notes and append to the relevant page(s) |
|
||||
|
||||
**Record in each page's prompt frontmatter** when refs exist:
|
||||
|
||||
```yaml
|
||||
references:
|
||||
- ref_id: 01
|
||||
filename: 01-ref-scene.png
|
||||
usage: style
|
||||
traits: "muted earth tones, soft-edged ink wash, low-contrast backgrounds"
|
||||
```
|
||||
|
||||
Character consistency is driven by **text descriptions** in `characters/characters.md` (written in Step 3) that get embedded inline in every page prompt (Step 5). The optional PNG character sheet generated in Step 7.1 is a human-facing review artifact, not an input to `image_generate`.
|
||||
|
||||
## Options
|
||||
|
||||
### Visual Dimensions
|
||||
|
||||
| Option | Values | Description |
|
||||
|--------|--------|-------------|
|
||||
| Art | ligne-claire (default), manga, realistic, ink-brush, chalk, minimalist | Art style / rendering technique |
|
||||
| Tone | neutral (default), warm, dramatic, romantic, energetic, vintage, action | Mood / atmosphere |
|
||||
| Layout | standard (default), cinematic, dense, splash, mixed, webtoon, four-panel | Panel arrangement |
|
||||
| Aspect | 3:4 (default, portrait), 4:3 (landscape), 16:9 (widescreen) | Page aspect ratio |
|
||||
| Language | auto (default), zh, en, ja, etc. | Output language |
|
||||
| Refs | File paths | Reference images used for style / palette trait extraction (not passed to the image model). See [Reference Images](#reference-images) above. |
|
||||
|
||||
### Partial Workflow Options
|
||||
|
||||
| Option | Description |
|
||||
|--------|-------------|
|
||||
| Storyboard only | Generate storyboard only, skip prompts and images |
|
||||
| Prompts only | Generate storyboard + prompts, skip images |
|
||||
| Images only | Generate images from existing prompts directory |
|
||||
| Regenerate N | Regenerate specific page(s) only (e.g., `3` or `2,5,8`) |
|
||||
|
||||
Details: [references/partial-workflows.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/partial-workflows.md)
|
||||
|
||||
### Art, Tone & Preset Catalogue
|
||||
|
||||
- **Art styles** (6): `ligne-claire`, `manga`, `realistic`, `ink-brush`, `chalk`, `minimalist`. Full definitions at `references/art-styles/<style>.md`.
|
||||
- **Tones** (7): `neutral`, `warm`, `dramatic`, `romantic`, `energetic`, `vintage`, `action`. Full definitions at `references/tones/<tone>.md`.
|
||||
- **Presets** (5) with special rules beyond plain art+tone:
|
||||
|
||||
| Preset | Equivalent | Hook |
|
||||
|--------|-----------|------|
|
||||
| `ohmsha` | manga + neutral | Visual metaphors, no talking heads, gadget reveals |
|
||||
| `wuxia` | ink-brush + action | Qi effects, combat visuals, atmospheric |
|
||||
| `shoujo` | manga + romantic | Decorative elements, eye details, romantic beats |
|
||||
| `concept-story` | manga + warm | Visual symbol system, growth arc, dialogue+action balance |
|
||||
| `four-panel` | minimalist + neutral + four-panel layout | 起承转合 structure, B&W + spot color, stick-figure characters |
|
||||
|
||||
Full rules at `references/presets/<preset>.md` — load the file when a preset is picked.
|
||||
|
||||
- **Compatibility matrix** and **content-signal → preset** table live in [references/auto-selection.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/auto-selection.md). Read it before recommending combinations in Step 2.
|
||||
|
||||
## File Structure
|
||||
|
||||
Output directory: `comic/{topic-slug}/`
|
||||
- Slug: 2-4 words kebab-case from topic (e.g., `alan-turing-bio`)
|
||||
- Conflict: append timestamp (e.g., `turing-story-20260118-143052`)
|
||||
|
||||
**Contents**:
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `source-{slug}.md` | Saved source content (kebab-case slug matches the output directory) |
|
||||
| `analysis.md` | Content analysis |
|
||||
| `storyboard.md` | Storyboard with panel breakdown |
|
||||
| `characters/characters.md` | Character definitions |
|
||||
| `characters/characters.png` | Character reference sheet (downloaded from `image_generate`) |
|
||||
| `prompts/NN-{cover\|page}-[slug].md` | Generation prompts |
|
||||
| `NN-{cover\|page}-[slug].png` | Generated images (downloaded from `image_generate`) |
|
||||
| `refs/NN-ref-{slug}.{ext}` | User-supplied reference images (optional, for provenance) |
|
||||
|
||||
## Language Handling
|
||||
|
||||
**Detection Priority**:
|
||||
1. User-specified language (explicit option)
|
||||
2. User's conversation language
|
||||
3. Source content language
|
||||
|
||||
**Rule**: Use user's input language for ALL interactions:
|
||||
- Storyboard outlines and scene descriptions
|
||||
- Image generation prompts
|
||||
- User selection options and confirmations
|
||||
- Progress updates, questions, errors, summaries
|
||||
|
||||
Technical terms remain in English.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Progress Checklist
|
||||
|
||||
```
|
||||
Comic Progress:
|
||||
- [ ] Step 1: Setup & Analyze
|
||||
- [ ] 1.1 Analyze content
|
||||
- [ ] 1.2 Check existing directory
|
||||
- [ ] Step 2: Confirmation - Style & options ⚠️ REQUIRED
|
||||
- [ ] Step 3: Generate storyboard + characters
|
||||
- [ ] Step 4: Review outline (conditional)
|
||||
- [ ] Step 5: Generate prompts
|
||||
- [ ] Step 6: Review prompts (conditional)
|
||||
- [ ] Step 7: Generate images
|
||||
- [ ] 7.1 Generate character sheet (if needed) → characters/characters.png
|
||||
- [ ] 7.2 Generate pages (with character descriptions embedded in prompt)
|
||||
- [ ] Step 8: Completion report
|
||||
```
|
||||
|
||||
### Flow
|
||||
|
||||
```
|
||||
Input → Analyze → [Check Existing?] → [Confirm: Style + Reviews] → Storyboard → [Review?] → Prompts → [Review?] → Images → Complete
|
||||
```
|
||||
|
||||
### Step Summary
|
||||
|
||||
| Step | Action | Key Output |
|
||||
|------|--------|------------|
|
||||
| 1.1 | Analyze content | `analysis.md`, `source-{slug}.md` |
|
||||
| 1.2 | Check existing directory | Handle conflicts |
|
||||
| 2 | Confirm style, focus, audience, reviews | User preferences |
|
||||
| 3 | Generate storyboard + characters | `storyboard.md`, `characters/` |
|
||||
| 4 | Review outline (if requested) | User approval |
|
||||
| 5 | Generate prompts | `prompts/*.md` |
|
||||
| 6 | Review prompts (if requested) | User approval |
|
||||
| 7.1 | Generate character sheet (if needed) | `characters/characters.png` |
|
||||
| 7.2 | Generate pages | `*.png` files |
|
||||
| 8 | Completion report | Summary |
|
||||
|
||||
### User Questions
|
||||
|
||||
Use the `clarify` tool to confirm options. Since `clarify` handles one question at a time, ask the most important question first and proceed sequentially. See [references/workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/workflow.md) for the full Step 2 question set.
|
||||
|
||||
**Timeout handling (CRITICAL)**: `clarify` can return `"The user did not provide a response within the time limit. Use your best judgement to make the choice and proceed."` — this is NOT user consent to default everything.
|
||||
|
||||
- Treat it as a default **for that one question only**. Continue asking the remaining Step 2 questions in sequence; each question is an independent consent point.
|
||||
- **Surface the default to the user visibly** in your next message so they have a chance to correct it: e.g. `"Style: defaulted to ohmsha preset (clarify timed out). Say the word to switch."` — an unreported default is indistinguishable from never having asked.
|
||||
- Do NOT collapse Step 2 into a single "use all defaults" pass after one timeout. If the user is genuinely absent, they will be equally absent for all five questions — but they can correct visible defaults when they return, and cannot correct invisible ones.
|
||||
|
||||
### Step 7: Image Generation
|
||||
|
||||
Use Hermes' built-in `image_generate` tool for all image rendering. Its schema accepts only `prompt` and `aspect_ratio` (`landscape` | `portrait` | `square`); it **returns a URL**, not a local file. Every generated page or character sheet must therefore be downloaded to the output directory.
|
||||
|
||||
**Prompt file requirement (hard)**: write each image's full, final prompt to a standalone file under `prompts/` (naming: `NN-{type}-[slug].md`) BEFORE calling `image_generate`. The prompt file is the reproducibility record.
|
||||
|
||||
**Aspect ratio mapping** — the storyboard's `aspect_ratio` field maps to `image_generate`'s format as follows:
|
||||
|
||||
| Storyboard ratio | `image_generate` format |
|
||||
|------------------|-------------------------|
|
||||
| `3:4`, `9:16`, `2:3` | `portrait` |
|
||||
| `4:3`, `16:9`, `3:2` | `landscape` |
|
||||
| `1:1` | `square` |
|
||||
|
||||
**Download step** — after every `image_generate` call:
|
||||
1. Read the URL from the tool result
|
||||
2. Fetch the image bytes using an **absolute** output path, e.g.
|
||||
`curl -fsSL "<url>" -o /abs/path/to/comic/<slug>/NN-page-<slug>.png`
|
||||
3. Verify the file exists and is non-empty at that exact path before proceeding to the next page
|
||||
|
||||
**Never rely on shell CWD persistence for `-o` paths.** The terminal tool's persistent-shell CWD can change between batches (session expiry, `TERMINAL_LIFETIME_SECONDS`, a failed `cd` that leaves you in the wrong directory). `curl -o relative/path.png` is a silent footgun: if CWD has drifted, the file lands somewhere else with no error. **Always pass a fully-qualified absolute path to `-o`**, or pass `workdir=<abs path>` to the terminal tool. Incident Apr 2026: pages 06-09 of a 10-page comic landed at the repo root instead of `comic/<slug>/` because batch 3 inherited a stale CWD from batch 2 and `curl -o 06-page-skills.png` wrote to the wrong directory. The agent then spent several turns claiming the files existed where they didn't.
|
||||
|
||||
**7.1 Character sheet** — generate it (to `characters/characters.png`, aspect `landscape`) when the comic is multi-page with recurring characters. Skip for simple presets (e.g., four-panel minimalist) or single-page comics. The prompt file at `characters/characters.md` must exist before invoking `image_generate`. The rendered PNG is a **human-facing review artifact** (so the user can visually verify character design) and a reference for later regenerations or manual prompt edits — it does **not** drive Step 7.2. Page prompts are already written in Step 5 from the **text descriptions** in `characters/characters.md`; `image_generate` cannot accept images as visual input.
|
||||
|
||||
**7.2 Pages** — each page's prompt MUST already be at `prompts/NN-{cover|page}-[slug].md` before invoking `image_generate`. Because `image_generate` is prompt-only, character consistency is enforced by **embedding character descriptions (sourced from `characters/characters.md`) inline in every page prompt during Step 5**. The embedding is done uniformly whether or not a PNG sheet is produced in 7.1; the PNG is only a review/regeneration aid.
|
||||
|
||||
**Backup rule**: existing `prompts/…md` and `…png` files → rename with `-backup-YYYYMMDD-HHMMSS` suffix before regenerating.
|
||||
|
||||
Full step-by-step workflow (analysis, storyboard, review gates, regeneration variants): [references/workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/workflow.md).
|
||||
|
||||
## References
|
||||
|
||||
**Core Templates**:
|
||||
- [analysis-framework.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/analysis-framework.md) - Deep content analysis
|
||||
- [character-template.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/character-template.md) - Character definition format
|
||||
- [storyboard-template.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/storyboard-template.md) - Storyboard structure
|
||||
- [ohmsha-guide.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/ohmsha-guide.md) - Ohmsha manga specifics
|
||||
|
||||
**Style Definitions**:
|
||||
- `references/art-styles/` - Art styles (ligne-claire, manga, realistic, ink-brush, chalk, minimalist)
|
||||
- `references/tones/` - Tones (neutral, warm, dramatic, romantic, energetic, vintage, action)
|
||||
- `references/presets/` - Presets with special rules (ohmsha, wuxia, shoujo, concept-story, four-panel)
|
||||
- `references/layouts/` - Layouts (standard, cinematic, dense, splash, mixed, webtoon, four-panel)
|
||||
|
||||
**Workflow**:
|
||||
- [workflow.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/workflow.md) - Full workflow details
|
||||
- [auto-selection.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/auto-selection.md) - Content signal analysis
|
||||
- [partial-workflows.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\baoyu-comic/references/partial-workflows.md) - Partial workflow options
|
||||
|
||||
## Page Modification
|
||||
|
||||
| Action | Steps |
|
||||
|--------|-------|
|
||||
| **Edit** | **Update prompt file FIRST** → regenerate image → download new PNG |
|
||||
| **Add** | Create prompt at position → generate with character descriptions embedded → renumber subsequent → update storyboard |
|
||||
| **Delete** | Remove files → renumber subsequent → update storyboard |
|
||||
|
||||
**IMPORTANT**: When updating pages, ALWAYS update the prompt file (`prompts/NN-{cover|page}-[slug].md`) FIRST before regenerating. This ensures changes are documented and reproducible.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Image generation: 10-30 seconds per page; auto-retry once on failure
|
||||
- **Always download** the URL returned by `image_generate` to a local PNG — downstream tooling (and the user's review) expects files in the output directory, not ephemeral URLs
|
||||
- **Use absolute paths for `curl -o`** — never rely on persistent-shell CWD across batches. Silent footgun: files land in the wrong directory and subsequent `ls` on the intended path shows nothing. See Step 7 "Download step".
|
||||
- Use stylized alternatives for sensitive public figures
|
||||
- **Step 2 confirmation required** - do not skip
|
||||
- **Steps 4/6 conditional** - only if user requested in Step 2
|
||||
- **Step 7.1 character sheet** - recommended for multi-page comics, optional for simple presets. The PNG is a review/regeneration aid; page prompts (written in Step 5) use the text descriptions in `characters/characters.md`, not the PNG. `image_generate` does not accept images as visual input
|
||||
- **Strip secrets** — scan source content for API keys, tokens, or credentials before writing any output file
|
||||
@@ -0,0 +1,616 @@
|
||||
---
|
||||
title: "Comfyui — Generate images, video, and audio via diffusion workflows"
|
||||
sidebar_label: "Comfyui"
|
||||
description: "Generate images, video, and audio via diffusion workflows"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Comfyui
|
||||
|
||||
Generate images, video, and audio via diffusion workflows.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/comfyui` |
|
||||
| Path | `optional-skills/creative\comfyui` |
|
||||
| Version | `5.1.0` |
|
||||
| Author | ['kshitijk4poor', 'alt-glitch', 'purzbeats'] |
|
||||
| License | MIT |
|
||||
| Platforms | macos, linux, windows |
|
||||
| Tags | `comfyui`, `image-generation`, `stable-diffusion`, `flux`, `sd3`, `wan-video`, `hunyuan-video`, `creative`, `generative-ai`, `video-generation` |
|
||||
| Related skills | [`stable-diffusion`](/docs/user-guide/skills/optional/mlops/mlops-stable-diffusion) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# ComfyUI
|
||||
|
||||
Generate images, video, audio, and 3D content through ComfyUI using the
|
||||
official `comfy-cli` for setup/lifecycle and direct REST/WebSocket API
|
||||
for workflow execution.
|
||||
|
||||
## What's in this skill
|
||||
|
||||
**Reference docs (`references/`):**
|
||||
|
||||
- `official-cli.md` — every `comfy ...` command, with flags
|
||||
- `rest-api.md` — REST + WebSocket endpoints (local + cloud), payload schemas
|
||||
- `workflow-format.md` — API-format JSON, common node types, param mapping
|
||||
- `template-integrity.md` — converting `comfyui-workflow-templates` from
|
||||
editor format to API format: Reroute bypass, dotted dynamic-input keys
|
||||
(`values.a`, `resize_type.width`), Cloud quirks (302 redirect, 1 concurrent
|
||||
free-tier job, 1080p VRAM ceiling), Discord-compatible ffmpeg stitch.
|
||||
Authored by [@purzbeats](https://github.com/purzbeats). Load this whenever
|
||||
you're starting from an official template.
|
||||
|
||||
**Scripts (`scripts/`):**
|
||||
|
||||
| Script | Purpose |
|
||||
|--------|---------|
|
||||
| `_common.py` | Shared HTTP, cloud routing, node catalogs (don't run directly) |
|
||||
| `hardware_check.py` | Probe GPU/VRAM/disk → recommend local vs Comfy Cloud |
|
||||
| `comfyui_setup.sh` | Hardware check + comfy-cli + ComfyUI install + launch + verify |
|
||||
| `extract_schema.py` | Read a workflow → list controllable params + model deps |
|
||||
| `check_deps.py` | Check workflow against running server → list missing nodes/models |
|
||||
| `auto_fix_deps.py` | Run check_deps then `comfy node install` / `comfy model download` |
|
||||
| `run_workflow.py` | Inject params, submit, monitor, download outputs (HTTP or WS) |
|
||||
| `run_batch.py` | Submit a workflow N times with sweeps, parallel up to your tier |
|
||||
| `ws_monitor.py` | Real-time WebSocket viewer for executing jobs (live progress) |
|
||||
| `health_check.py` | Verification checklist runner — comfy-cli + server + models + smoke test |
|
||||
| `fetch_logs.py` | Pull traceback / status messages for a given prompt_id |
|
||||
|
||||
**Example workflows (`workflows/`):** SD 1.5, SDXL, Flux Dev, SDXL img2img,
|
||||
SDXL inpaint, ESRGAN upscale, AnimateDiff video, Wan T2V. See
|
||||
`workflows/README.md`.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks to generate images with Stable Diffusion, SDXL, Flux, SD3, etc.
|
||||
- User wants to run a specific ComfyUI workflow file
|
||||
- User wants to chain generative steps (txt2img → upscale → face restore)
|
||||
- User needs ControlNet, inpainting, img2img, or other advanced pipelines
|
||||
- User asks to manage ComfyUI queue, check models, or install custom nodes
|
||||
- User wants video/audio/3D generation via AnimateDiff, Hunyuan, Wan, AudioCraft, etc.
|
||||
|
||||
## Architecture: Two Layers
|
||||
|
||||
<!-- ascii-guard-ignore -->
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Layer 1: comfy-cli (official lifecycle tool) │
|
||||
│ Setup, server lifecycle, custom nodes, models │
|
||||
│ → comfy install / launch / stop / node / model │
|
||||
└─────────────────────────┬───────────────────────────┘
|
||||
│
|
||||
┌─────────────────────────▼───────────────────────────┐
|
||||
│ Layer 2: REST/WebSocket API + skill scripts │
|
||||
│ Workflow execution, param injection, monitoring │
|
||||
│ POST /api/prompt, GET /api/view, WS /ws │
|
||||
│ → run_workflow.py, run_batch.py, ws_monitor.py │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
**Why two layers?** The official CLI is excellent for installation and server
|
||||
management but has minimal workflow execution support. The REST/WS API fills
|
||||
that gap — the scripts handle param injection, execution monitoring, and
|
||||
output download that the CLI doesn't do.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Detect environment
|
||||
|
||||
```bash
|
||||
# What's available?
|
||||
command -v comfy >/dev/null 2>&1 && echo "comfy-cli: installed"
|
||||
curl -s http://127.0.0.1:8188/system_stats 2>/dev/null && echo "server: running"
|
||||
|
||||
# Can this machine run ComfyUI locally? (GPU/VRAM/disk check)
|
||||
python scripts/hardware_check.py
|
||||
```
|
||||
|
||||
If nothing is installed, see **Setup & Onboarding** below — but always run the
|
||||
hardware check first.
|
||||
|
||||
### One-line health check
|
||||
|
||||
```bash
|
||||
python scripts/health_check.py
|
||||
# → JSON: comfy_cli on PATH? server reachable? at least one checkpoint? smoke-test passes?
|
||||
```
|
||||
|
||||
## Core Workflow
|
||||
|
||||
### Step 1: Get a workflow JSON in API format
|
||||
|
||||
Workflows must be in API format (each node has `class_type`). They come from:
|
||||
|
||||
- ComfyUI web UI → **Workflow → Export (API)** (newer UI) or
|
||||
the legacy "Save (API Format)" button (older UI)
|
||||
- This skill's `workflows/` directory (ready-to-run examples)
|
||||
- Community downloads (civitai, Reddit, Discord) — usually editor format,
|
||||
must be loaded into ComfyUI then re-exported
|
||||
|
||||
Editor format (top-level `nodes` and `links` arrays) is **not directly
|
||||
executable**. The scripts detect this and tell you to re-export.
|
||||
|
||||
### Step 2: See what's controllable
|
||||
|
||||
```bash
|
||||
python scripts/extract_schema.py workflow_api.json --summary-only
|
||||
# → {"parameter_count": 12, "has_negative_prompt": true, "has_seed": true, ...}
|
||||
|
||||
python scripts/extract_schema.py workflow_api.json
|
||||
# → full schema with parameters, model deps, embedding refs
|
||||
```
|
||||
|
||||
### Step 3: Run with parameters
|
||||
|
||||
```bash
|
||||
# Local (defaults to http://127.0.0.1:8188)
|
||||
python scripts/run_workflow.py \
|
||||
--workflow workflow_api.json \
|
||||
--args '{"prompt": "a beautiful sunset over mountains", "seed": -1, "steps": 30}' \
|
||||
--output-dir ./outputs
|
||||
|
||||
# Cloud (export API key once; uses correct /api routing automatically)
|
||||
export COMFY_CLOUD_API_KEY="comfyui-..."
|
||||
python scripts/run_workflow.py \
|
||||
--workflow workflow_api.json \
|
||||
--args '{"prompt": "..."}' \
|
||||
--host https://cloud.comfy.org \
|
||||
--output-dir ./outputs
|
||||
|
||||
# Real-time progress via WebSocket (requires `pip install websocket-client`)
|
||||
python scripts/run_workflow.py \
|
||||
--workflow flux_dev.json \
|
||||
--args '{"prompt": "..."}' \
|
||||
--ws
|
||||
|
||||
# img2img / inpaint: pass --input-image to upload + reference automatically
|
||||
python scripts/run_workflow.py \
|
||||
--workflow sdxl_img2img.json \
|
||||
--input-image image=./photo.png \
|
||||
--args '{"prompt": "make it watercolor", "denoise": 0.6}'
|
||||
|
||||
# Batch / sweep: 8 random seeds, parallel up to cloud tier limit
|
||||
python scripts/run_batch.py \
|
||||
--workflow sdxl.json \
|
||||
--args '{"prompt": "abstract"}' \
|
||||
--count 8 --randomize-seed --parallel 3 \
|
||||
--output-dir ./outputs/batch
|
||||
```
|
||||
|
||||
`-1` for `seed` (or omitting it with `--randomize-seed`) generates a fresh
|
||||
random seed per run.
|
||||
|
||||
### Step 4: Present results
|
||||
|
||||
The scripts emit JSON to stdout describing every output file:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"prompt_id": "abc-123",
|
||||
"outputs": [
|
||||
{"file": "./outputs/sdxl_00001_.png", "node_id": "9",
|
||||
"type": "image", "filename": "sdxl_00001_.png"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Decision Tree
|
||||
|
||||
| User says | Tool | Command |
|
||||
|-----------|------|---------|
|
||||
| **Lifecycle (use comfy-cli)** | | |
|
||||
| "install ComfyUI" | comfy-cli | `bash scripts/comfyui_setup.sh` |
|
||||
| "start ComfyUI" | comfy-cli | `comfy launch --background` |
|
||||
| "stop ComfyUI" | comfy-cli | `comfy stop` |
|
||||
| "install X node" | comfy-cli | `comfy node install <name>` |
|
||||
| "download X model" | comfy-cli | `comfy model download --url <url> --relative-path models/checkpoints` |
|
||||
| "list installed models" | comfy-cli | `comfy model list` |
|
||||
| "list installed nodes" | comfy-cli | `comfy node show installed` |
|
||||
| **Execution (use scripts)** | | |
|
||||
| "is everything ready?" | script | `health_check.py` (optionally with `--workflow X --smoke-test`) |
|
||||
| "what can I change in this workflow?" | script | `extract_schema.py W.json` |
|
||||
| "check if W's deps are met" | script | `check_deps.py W.json` |
|
||||
| "fix missing deps" | script | `auto_fix_deps.py W.json` |
|
||||
| "generate an image" | script | `run_workflow.py --workflow W --args '{...}'` |
|
||||
| "use this image" (img2img) | script | `run_workflow.py --input-image image=./x.png ...` |
|
||||
| "8 variations with random seeds" | script | `run_batch.py --count 8 --randomize-seed ...` |
|
||||
| "show me live progress" | script | `ws_monitor.py --prompt-id <id>` |
|
||||
| "fetch the error from job X" | script | `fetch_logs.py <prompt_id>` |
|
||||
| **Direct REST** | | |
|
||||
| "what's in the queue?" | REST | `curl http://HOST:8188/queue` (local) or `--host https://cloud.comfy.org` |
|
||||
| "cancel that" | REST | `curl -X POST http://HOST:8188/interrupt` |
|
||||
| "free GPU memory" | REST | `curl -X POST http://HOST:8188/free` |
|
||||
|
||||
## Setup & Onboarding
|
||||
|
||||
When a user asks to set up ComfyUI, **the FIRST thing to do is ask whether
|
||||
they want Comfy Cloud (hosted, zero install, API key) or Local (install
|
||||
ComfyUI on their machine)**. Don't start running install commands or hardware
|
||||
checks until they've answered.
|
||||
|
||||
**Official docs:** https://docs.comfy.org/installation
|
||||
**CLI docs:** https://docs.comfy.org/comfy-cli/getting-started
|
||||
**Cloud docs:** https://docs.comfy.org/get_started/cloud
|
||||
**Cloud API:** https://docs.comfy.org/development/cloud/overview
|
||||
|
||||
### Step 0: Ask Local vs Cloud (ALWAYS FIRST)
|
||||
|
||||
Suggested script:
|
||||
|
||||
> "Do you want to run ComfyUI locally on your machine, or use Comfy Cloud?
|
||||
>
|
||||
> - **Comfy Cloud** — hosted on RTX 6000 Pro GPUs, all common models pre-installed,
|
||||
> zero setup. Requires an API key (paid subscription required to actually run
|
||||
> workflows; free tier is read-only). Best if you don't have a capable GPU.
|
||||
> - **Local** — free, but your machine MUST meet the hardware requirements:
|
||||
> - NVIDIA GPU with **≥6 GB VRAM** (≥8 GB for SDXL, ≥12 GB for Flux/video), OR
|
||||
> - AMD GPU with ROCm support (Linux), OR
|
||||
> - Apple Silicon Mac (M1+) with **≥16 GB unified memory** (≥32 GB recommended).
|
||||
> - Intel Macs and machines with no GPU will NOT work — use Cloud instead.
|
||||
>
|
||||
> Which would you like?"
|
||||
|
||||
Routing:
|
||||
|
||||
- **Cloud** → skip to **Path A**.
|
||||
- **Local** → run hardware check first, then pick a path from Paths B–E based on the verdict.
|
||||
- **Unsure** → run the hardware check and let the verdict decide.
|
||||
|
||||
### Step 1: Verify Hardware (ONLY if user chose local)
|
||||
|
||||
```bash
|
||||
python scripts/hardware_check.py --json
|
||||
# Optional: also probe `torch` for actual CUDA/MPS:
|
||||
python scripts/hardware_check.py --json --check-pytorch
|
||||
```
|
||||
|
||||
| Verdict | Meaning | Action |
|
||||
|------------|---------------------------------------------------------------|--------|
|
||||
| `ok` | ≥8 GB VRAM (discrete) OR ≥32 GB unified (Apple Silicon) | Local install — use `comfy_cli_flag` from report |
|
||||
| `marginal` | SD1.5 works; SDXL tight; Flux/video unlikely | Local OK for light workflows, else **Path A (Cloud)** |
|
||||
| `cloud` | No usable GPU, <6 GB VRAM, <16 GB Apple unified, Intel Mac, Rosetta Python | **Switch to Cloud** unless user explicitly forces local |
|
||||
|
||||
The script also surfaces `wsl: true` (WSL2 with NVIDIA passthrough) and
|
||||
`rosetta: true` (x86_64 Python on Apple Silicon — must reinstall as ARM64).
|
||||
|
||||
If verdict is `cloud` but the user wants local, do not proceed silently.
|
||||
Show the `notes` array verbatim and ask whether they want to (a) switch to
|
||||
Cloud or (b) force a local install (will OOM or be unusably slow on modern models).
|
||||
|
||||
### Choosing an Installation Path
|
||||
|
||||
Use the hardware check first. The table below is the fallback for when the
|
||||
user has already told you their hardware:
|
||||
|
||||
| Situation | Recommended Path |
|
||||
|-----------|------------------|
|
||||
| `verdict: cloud` from hardware check | **Path A: Comfy Cloud** |
|
||||
| No GPU / want to try without commitment | **Path A: Comfy Cloud** |
|
||||
| Windows + NVIDIA + non-technical | **Path B: ComfyUI Desktop** |
|
||||
| Windows + NVIDIA + technical | **Path C: Portable** or **Path D: comfy-cli** |
|
||||
| Linux + any GPU | **Path D: comfy-cli** (easiest) |
|
||||
| macOS + Apple Silicon | **Path B: Desktop** or **Path D: comfy-cli** |
|
||||
| Headless / server / CI / agents | **Path D: comfy-cli** |
|
||||
|
||||
For the fully automated path (hardware check → install → launch → verify):
|
||||
|
||||
```bash
|
||||
bash scripts/comfyui_setup.sh
|
||||
# Or with overrides:
|
||||
bash scripts/comfyui_setup.sh --m-series --port=8190 --workspace=/data/comfy
|
||||
```
|
||||
|
||||
It runs `hardware_check.py` internally, refuses to install locally when the
|
||||
verdict is `cloud` (unless `--force-cloud-override`), picks the right
|
||||
`comfy-cli` flag, and prefers `pipx`/`uvx` over global `pip` to avoid polluting
|
||||
system Python.
|
||||
|
||||
---
|
||||
|
||||
### Path A: Comfy Cloud (No Local Install)
|
||||
|
||||
For users without a capable GPU or who want zero setup. Hosted on RTX 6000 Pro.
|
||||
|
||||
**Docs:** https://docs.comfy.org/get_started/cloud
|
||||
|
||||
1. Sign up at https://comfy.org/cloud
|
||||
2. Generate an API key at https://platform.comfy.org/login
|
||||
3. Set the key:
|
||||
```bash
|
||||
export COMFY_CLOUD_API_KEY="your-comfyui-key"
|
||||
```
|
||||
4. Run workflows:
|
||||
```bash
|
||||
python scripts/run_workflow.py \
|
||||
--workflow workflows/flux_dev_txt2img.json \
|
||||
--args '{"prompt": "..."}' \
|
||||
--host https://cloud.comfy.org \
|
||||
--output-dir ./outputs
|
||||
```
|
||||
|
||||
**Pricing:** https://www.comfy.org/cloud/pricing
|
||||
**Concurrent jobs:** Free/Standard 1, Creator 3, Pro 5. Free tier
|
||||
**cannot run workflows via API** — only browse models. Paid subscription
|
||||
required for `/api/prompt`, `/api/upload/*`, `/api/view`, etc.
|
||||
|
||||
---
|
||||
|
||||
### Path B: ComfyUI Desktop (Windows / macOS)
|
||||
|
||||
One-click installer for non-technical users. Currently Beta.
|
||||
|
||||
**Docs:** https://docs.comfy.org/installation/desktop
|
||||
- **Windows (NVIDIA):** https://download.comfy.org/windows/nsis/x64
|
||||
- **macOS (Apple Silicon):** https://comfy.org
|
||||
|
||||
Linux is **not supported** for Desktop — use Path D.
|
||||
|
||||
---
|
||||
|
||||
### Path C: ComfyUI Portable (Windows Only)
|
||||
|
||||
**Docs:** https://docs.comfy.org/installation/comfyui_portable_windows
|
||||
|
||||
Download from https://github.com/comfyanonymous/ComfyUI/releases, extract,
|
||||
run `run_nvidia_gpu.bat`. Update via `update/update_comfyui_stable.bat`.
|
||||
|
||||
---
|
||||
|
||||
### Path D: comfy-cli (All Platforms — Recommended for Agents)
|
||||
|
||||
The official CLI is the best path for headless/automated setups.
|
||||
|
||||
**Docs:** https://docs.comfy.org/comfy-cli/getting-started
|
||||
|
||||
#### Install comfy-cli
|
||||
|
||||
```bash
|
||||
# Recommended:
|
||||
pipx install comfy-cli
|
||||
# Or use uvx without installing:
|
||||
uvx --from comfy-cli comfy --help
|
||||
# Or (if pipx/uvx unavailable):
|
||||
pip install --user comfy-cli
|
||||
```
|
||||
|
||||
Disable analytics non-interactively:
|
||||
```bash
|
||||
comfy --skip-prompt tracking disable
|
||||
```
|
||||
|
||||
#### Install ComfyUI
|
||||
|
||||
```bash
|
||||
comfy --skip-prompt install --nvidia # NVIDIA (CUDA)
|
||||
comfy --skip-prompt install --amd # AMD (ROCm, Linux)
|
||||
comfy --skip-prompt install --m-series # Apple Silicon (MPS)
|
||||
comfy --skip-prompt install --cpu # CPU only (slow)
|
||||
comfy --skip-prompt install --nvidia --fast-deps # uv-based dep resolution
|
||||
```
|
||||
|
||||
Default location: `~/comfy/ComfyUI` (Linux), `~/Documents/comfy/ComfyUI`
|
||||
(macOS/Win). Override with `comfy --workspace /custom/path install`.
|
||||
|
||||
#### Launch / verify
|
||||
|
||||
```bash
|
||||
comfy launch --background # background daemon on :8188
|
||||
comfy launch -- --listen 0.0.0.0 --port 8190 # LAN-accessible custom port
|
||||
curl -s http://127.0.0.1:8188/system_stats # health check
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Path E: Manual Install (Advanced / Unsupported Hardware)
|
||||
|
||||
For Ascend NPU, Cambricon MLU, Intel Arc, or other unsupported hardware.
|
||||
|
||||
**Docs:** https://docs.comfy.org/installation/manual_install
|
||||
|
||||
```bash
|
||||
git clone https://github.com/comfyanonymous/ComfyUI.git
|
||||
cd ComfyUI
|
||||
pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu130
|
||||
pip install -r requirements.txt
|
||||
python main.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Post-Install: Download Models
|
||||
|
||||
```bash
|
||||
# SDXL (general purpose, ~6.5 GB)
|
||||
comfy model download \
|
||||
--url "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors" \
|
||||
--relative-path models/checkpoints
|
||||
|
||||
# SD 1.5 (lighter, ~4 GB, good for 6 GB cards)
|
||||
comfy model download \
|
||||
--url "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.safetensors" \
|
||||
--relative-path models/checkpoints
|
||||
|
||||
# Flux Dev fp8 (smaller variant, ~12 GB)
|
||||
comfy model download \
|
||||
--url "https://huggingface.co/Comfy-Org/flux1-dev/resolve/main/flux1-dev-fp8.safetensors" \
|
||||
--relative-path models/checkpoints
|
||||
|
||||
# CivitAI (set token first):
|
||||
comfy model download \
|
||||
--url "https://civitai.com/api/download/models/128713" \
|
||||
--relative-path models/checkpoints \
|
||||
--set-civitai-api-token "YOUR_TOKEN"
|
||||
```
|
||||
|
||||
List installed: `comfy model list`.
|
||||
|
||||
### Post-Install: Install Custom Nodes
|
||||
|
||||
```bash
|
||||
comfy node install comfyui-impact-pack # popular utility pack
|
||||
comfy node install comfyui-animatediff-evolved # video generation
|
||||
comfy node install comfyui-controlnet-aux # ControlNet preprocessors
|
||||
comfy node install comfyui-essentials # common helpers
|
||||
comfy node update all
|
||||
comfy node install-deps --workflow=workflow.json # install everything a workflow needs
|
||||
```
|
||||
|
||||
### Post-Install: Verify
|
||||
|
||||
```bash
|
||||
python scripts/health_check.py
|
||||
# → comfy_cli on PATH? server reachable? checkpoints? smoke test?
|
||||
|
||||
python scripts/check_deps.py my_workflow.json
|
||||
# → are this workflow's nodes/models/embeddings installed?
|
||||
|
||||
python scripts/run_workflow.py \
|
||||
--workflow workflows/sd15_txt2img.json \
|
||||
--args '{"prompt": "test", "steps": 4}' \
|
||||
--output-dir ./test-outputs
|
||||
```
|
||||
|
||||
## Image Upload (img2img / Inpainting)
|
||||
|
||||
The simplest way is to use `--input-image` with `run_workflow.py`:
|
||||
|
||||
```bash
|
||||
python scripts/run_workflow.py \
|
||||
--workflow workflows/sdxl_img2img.json \
|
||||
--input-image image=./photo.png \
|
||||
--args '{"prompt": "make it cyberpunk", "denoise": 0.6}'
|
||||
```
|
||||
|
||||
The flag uploads `photo.png`, then injects its server-side filename into
|
||||
whatever schema parameter is named `image`. For inpainting, pass both:
|
||||
|
||||
```bash
|
||||
python scripts/run_workflow.py \
|
||||
--workflow workflows/sdxl_inpaint.json \
|
||||
--input-image image=./photo.png \
|
||||
--input-image mask_image=./mask.png \
|
||||
--args '{"prompt": "fill with flowers"}'
|
||||
```
|
||||
|
||||
Manual upload via REST:
|
||||
```bash
|
||||
curl -X POST "http://127.0.0.1:8188/upload/image" \
|
||||
-F "image=@photo.png" -F "type=input" -F "overwrite=true"
|
||||
# Returns: {"name": "photo.png", "subfolder": "", "type": "input"}
|
||||
|
||||
# Cloud equivalent:
|
||||
curl -X POST "https://cloud.comfy.org/api/upload/image" \
|
||||
-H "X-API-Key: $COMFY_CLOUD_API_KEY" \
|
||||
-F "image=@photo.png" -F "type=input" -F "overwrite=true"
|
||||
```
|
||||
|
||||
## Cloud Specifics
|
||||
|
||||
- **Base URL:** `https://cloud.comfy.org`
|
||||
- **Auth:** `X-API-Key` header (or `?token=KEY` for WebSocket)
|
||||
- **API key:** set `$COMFY_CLOUD_API_KEY` once and the scripts pick it up automatically
|
||||
- **Output download:** `/api/view` returns a 302 to a signed URL; the scripts
|
||||
follow it and strip `X-API-Key` before fetching from the storage backend
|
||||
(don't leak the API key to S3/CloudFront).
|
||||
- **Endpoint differences from local ComfyUI:**
|
||||
- `/api/object_info`, `/api/queue`, `/api/userdata` — **403 on free tier**;
|
||||
paid only.
|
||||
- `/history` is renamed to `/history_v2` on cloud (the scripts route
|
||||
automatically).
|
||||
- `/models/<folder>` is renamed to `/experiment/models/<folder>` on cloud
|
||||
(the scripts route automatically).
|
||||
- `clientId` in WebSocket is currently ignored — all connections for a
|
||||
user receive the same broadcast. Filter by `prompt_id` client-side.
|
||||
- `subfolder` is accepted on uploads but ignored — cloud has a flat namespace.
|
||||
- **Concurrent jobs:** Free/Standard: 1, Creator: 3, Pro: 5. Extras queue
|
||||
automatically. Use `run_batch.py --parallel N` to saturate your tier.
|
||||
|
||||
## Queue & System Management
|
||||
|
||||
```bash
|
||||
# Local
|
||||
curl -s http://127.0.0.1:8188/queue | python -m json.tool
|
||||
curl -X POST http://127.0.0.1:8188/queue -d '{"clear": true}' # cancel pending
|
||||
curl -X POST http://127.0.0.1:8188/interrupt # cancel running
|
||||
curl -X POST http://127.0.0.1:8188/free \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"unload_models": true, "free_memory": true}'
|
||||
|
||||
# Cloud — same paths under /api/, plus:
|
||||
python scripts/fetch_logs.py --tail-queue --host https://cloud.comfy.org
|
||||
```
|
||||
|
||||
## Pitfalls
|
||||
|
||||
1. **API format required** — every script and the `/api/prompt` endpoint expect
|
||||
API-format workflow JSON. The scripts detect editor format (top-level
|
||||
`nodes` and `links` arrays) and tell you to re-export via
|
||||
"Workflow → Export (API)" (newer UI) or "Save (API Format)" (older UI).
|
||||
|
||||
2. **Server must be running** — all execution requires a live server.
|
||||
`comfy launch --background` starts one. Verify with
|
||||
`curl http://127.0.0.1:8188/system_stats`.
|
||||
|
||||
3. **Model names are exact** — case-sensitive, includes file extension.
|
||||
`check_deps.py` does fuzzy matching (with/without extension and folder
|
||||
prefix), but the workflow itself must use the canonical name. Use
|
||||
`comfy model list` to discover what's installed.
|
||||
|
||||
4. **Missing custom nodes** — "class_type not found" means a required node
|
||||
isn't installed. `check_deps.py` reports which package to install;
|
||||
`auto_fix_deps.py` runs the install for you.
|
||||
|
||||
5. **Working directory** — `comfy-cli` auto-detects the ComfyUI workspace.
|
||||
If commands fail with "no workspace found", use
|
||||
`comfy --workspace /path/to/ComfyUI <command>` or
|
||||
`comfy set-default /path/to/ComfyUI`.
|
||||
|
||||
6. **Cloud free-tier API limits** — `/api/prompt`, `/api/view`, `/api/upload/*`,
|
||||
`/api/object_info` all return 403 on free accounts. `health_check.py` and
|
||||
`check_deps.py` handle this gracefully and surface a clear message.
|
||||
|
||||
7. **Timeout for video/audio workflows** — auto-detected when an output node
|
||||
is `VHS_VideoCombine`, `SaveVideo`, etc.; the default jumps from 300 s to
|
||||
900 s. Override explicitly with `--timeout 1800`.
|
||||
|
||||
8. **Path traversal in output filenames** — server-supplied filenames are
|
||||
passed through `safe_path_join` to refuse anything escaping `--output-dir`.
|
||||
Keep this protection on — workflows with custom save nodes can produce
|
||||
arbitrary paths.
|
||||
|
||||
9. **Workflow JSON is arbitrary code** — custom nodes run Python, so
|
||||
submitting an unknown workflow has the same trust profile as `eval`.
|
||||
Inspect workflows from untrusted sources before running.
|
||||
|
||||
10. **Auto-randomized seed** — pass `seed: -1` in `--args` (or use
|
||||
`--randomize-seed` and omit the seed) to get a fresh seed per run.
|
||||
The actual seed is logged to stderr.
|
||||
|
||||
11. **`tracking` prompt** — first run of `comfy` may prompt for analytics.
|
||||
Use `comfy --skip-prompt tracking disable` to skip non-interactively.
|
||||
`comfyui_setup.sh` does this for you.
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
Use `python scripts/health_check.py` to run the whole list at once. Manual:
|
||||
|
||||
- [ ] `hardware_check.py` verdict is `ok` OR the user explicitly chose Comfy Cloud
|
||||
- [ ] `comfy --version` works (or `uvx --from comfy-cli comfy --help`)
|
||||
- [ ] `curl http://HOST:PORT/system_stats` returns JSON
|
||||
- [ ] `comfy model list` shows at least one checkpoint (local) OR
|
||||
`/api/experiment/models/checkpoints` returns models (cloud)
|
||||
- [ ] Workflow JSON is in API format
|
||||
- [ ] `check_deps.py` reports `is_ready: true` (or only `node_check_skipped`
|
||||
on cloud free tier)
|
||||
- [ ] Test run with a small workflow completes; outputs land in `--output-dir`
|
||||
@@ -0,0 +1,379 @@
|
||||
---
|
||||
title: "Concept Diagrams — Generate flat, minimal educational SVG visuals as HTML"
|
||||
sidebar_label: "Concept Diagrams"
|
||||
description: "Generate flat, minimal educational SVG visuals as HTML"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Concept Diagrams
|
||||
|
||||
Generate flat, minimal educational SVG visuals as HTML.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/concept-diagrams` |
|
||||
| Path | `optional-skills/creative\concept-diagrams` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | v1k22 (original PR), ported into hermes-agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `diagrams`, `svg`, `visualization`, `education`, `physics`, `chemistry`, `engineering` |
|
||||
| Related skills | [`architecture-diagram`](/docs/user-guide/skills/bundled/creative/creative-architecture-diagram), [`excalidraw`](/docs/user-guide/skills/optional/creative/creative-excalidraw) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Concept Diagrams
|
||||
|
||||
Generate production-quality SVG diagrams with a unified flat, minimal design system. Output is a single self-contained HTML file that renders identically in any modern browser, with automatic light/dark mode.
|
||||
|
||||
## Scope
|
||||
|
||||
**Best suited for:**
|
||||
- Physics setups, chemistry mechanisms, math curves, biology
|
||||
- Physical objects (aircraft, turbines, smartphones, mechanical watches, cells)
|
||||
- Anatomy, cross-sections, exploded layer views
|
||||
- Floor plans, architectural conversions
|
||||
- Narrative journeys (lifecycle of X, process of Y)
|
||||
- Hub-spoke system integrations (smart city, IoT networks, electricity grids)
|
||||
- Educational / textbook-style visuals in any domain
|
||||
- Quantitative charts (grouped bars, energy profiles)
|
||||
|
||||
**Look elsewhere first for:**
|
||||
- Dedicated software / cloud infrastructure architecture with a dark tech aesthetic (consider `architecture-diagram` if available)
|
||||
- Hand-drawn whiteboard sketches (consider `excalidraw` if available)
|
||||
- Animated explainers or video output (consider an animation skill)
|
||||
|
||||
If a more specialized skill is available for the subject, prefer that. If none fits, this skill can serve as a general-purpose SVG diagram fallback — the output will carry the clean educational aesthetic described below, which is a reasonable default for almost any subject.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Decide on the diagram type (see Diagram Types below).
|
||||
2. Lay out components using the Design System rules.
|
||||
3. Write the full HTML page using `templates/template.html` as the wrapper — paste your SVG where the template says `<!-- PASTE SVG HERE -->`.
|
||||
4. Save as a standalone `.html` file (for example `~/my-diagram.html` or `./my-diagram.html`).
|
||||
5. User opens it directly in a browser — no server, no dependencies.
|
||||
|
||||
Optional: if the user wants a browsable gallery of multiple diagrams, see "Local Preview Server" at the bottom.
|
||||
|
||||
Load the HTML template:
|
||||
```
|
||||
skill_view(name="concept-diagrams", file_path="templates/template.html")
|
||||
```
|
||||
|
||||
The template embeds the full CSS design system (`c-*` color classes, text classes, light/dark variables, arrow marker styles). The SVG you generate relies on these classes being present on the hosting page.
|
||||
|
||||
---
|
||||
|
||||
## Design System
|
||||
|
||||
### Philosophy
|
||||
|
||||
- **Flat**: no gradients, drop shadows, blur, glow, or neon effects.
|
||||
- **Minimal**: show the essential. No decorative icons inside boxes.
|
||||
- **Consistent**: same colors, spacing, typography, and stroke widths across every diagram.
|
||||
- **Dark-mode ready**: all colors auto-adapt via CSS classes — no per-mode SVG.
|
||||
|
||||
### Color Palette
|
||||
|
||||
9 color ramps, each with 7 stops. Put the class name on a `<g>` or shape element; the template CSS handles both modes.
|
||||
|
||||
| Class | 50 (lightest) | 100 | 200 | 400 | 600 | 800 | 900 (darkest) |
|
||||
|------------|---------------|---------|---------|---------|---------|---------|---------------|
|
||||
| `c-purple` | #EEEDFE | #CECBF6 | #AFA9EC | #7F77DD | #534AB7 | #3C3489 | #26215C |
|
||||
| `c-teal` | #E1F5EE | #9FE1CB | #5DCAA5 | #1D9E75 | #0F6E56 | #085041 | #04342C |
|
||||
| `c-coral` | #FAECE7 | #F5C4B3 | #F0997B | #D85A30 | #993C1D | #712B13 | #4A1B0C |
|
||||
| `c-pink` | #FBEAF0 | #F4C0D1 | #ED93B1 | #D4537E | #993556 | #72243E | #4B1528 |
|
||||
| `c-gray` | #F1EFE8 | #D3D1C7 | #B4B2A9 | #888780 | #5F5E5A | #444441 | #2C2C2A |
|
||||
| `c-blue` | #E6F1FB | #B5D4F4 | #85B7EB | #378ADD | #185FA5 | #0C447C | #042C53 |
|
||||
| `c-green` | #EAF3DE | #C0DD97 | #97C459 | #639922 | #3B6D11 | #27500A | #173404 |
|
||||
| `c-amber` | #FAEEDA | #FAC775 | #EF9F27 | #BA7517 | #854F0B | #633806 | #412402 |
|
||||
| `c-red` | #FCEBEB | #F7C1C1 | #F09595 | #E24B4A | #A32D2D | #791F1F | #501313 |
|
||||
|
||||
#### Color Assignment Rules
|
||||
|
||||
Color encodes **meaning**, not sequence. Never cycle through colors like a rainbow.
|
||||
|
||||
- Group nodes by **category** — all nodes of the same type share one color.
|
||||
- Use `c-gray` for neutral/structural nodes (start, end, generic steps, users).
|
||||
- Use **2-3 colors per diagram**, not 6+.
|
||||
- Prefer `c-purple`, `c-teal`, `c-coral`, `c-pink` for general categories.
|
||||
- Reserve `c-blue`, `c-green`, `c-amber`, `c-red` for semantic meaning (info, success, warning, error).
|
||||
|
||||
Light/dark stop mapping (handled by the template CSS — just use the class):
|
||||
- Light mode: 50 fill + 600 stroke + 800 title / 600 subtitle
|
||||
- Dark mode: 800 fill + 200 stroke + 100 title / 200 subtitle
|
||||
|
||||
### Typography
|
||||
|
||||
Only two font sizes. No exceptions.
|
||||
|
||||
| Class | Size | Weight | Use |
|
||||
|-------|------|--------|-----|
|
||||
| `th` | 14px | 500 | Node titles, region labels |
|
||||
| `ts` | 12px | 400 | Subtitles, descriptions, arrow labels |
|
||||
| `t` | 14px | 400 | General text |
|
||||
|
||||
- **Sentence case always.** Never Title Case, never ALL CAPS.
|
||||
- Every `<text>` MUST carry a class (`t`, `ts`, or `th`). No unclassed text.
|
||||
- `dominant-baseline="central"` on all text inside boxes.
|
||||
- `text-anchor="middle"` for centered text in boxes.
|
||||
|
||||
**Width estimation (approx):**
|
||||
- 14px weight 500: ~8px per character
|
||||
- 12px weight 400: ~6.5px per character
|
||||
- Always verify: `box_width >= (char_count × px_per_char) + 48` (24px padding each side)
|
||||
|
||||
### Spacing & Layout
|
||||
|
||||
- **ViewBox**: `viewBox="0 0 680 H"` where H = content height + 40px buffer.
|
||||
- **Safe area**: x=40 to x=640, y=40 to y=(H-40).
|
||||
- **Between boxes**: 60px minimum gap.
|
||||
- **Inside boxes**: 24px horizontal padding, 12px vertical padding.
|
||||
- **Arrowhead gap**: 10px between arrowhead and box edge.
|
||||
- **Single-line box**: 44px height.
|
||||
- **Two-line box**: 56px height, 18px between title and subtitle baselines.
|
||||
- **Container padding**: 20px minimum inside every container.
|
||||
- **Max nesting**: 2-3 levels deep. Deeper gets unreadable at 680px width.
|
||||
|
||||
### Stroke & Shape
|
||||
|
||||
- **Stroke width**: 0.5px on all node borders. Not 1px, not 2px.
|
||||
- **Rect rounding**: `rx="8"` for nodes, `rx="12"` for inner containers, `rx="16"` to `rx="20"` for outer containers.
|
||||
- **Connector paths**: MUST have `fill="none"`. SVG defaults to `fill: black` otherwise.
|
||||
|
||||
### Arrow Marker
|
||||
|
||||
Include this `<defs>` block at the start of **every** SVG:
|
||||
|
||||
```xml
|
||||
<defs>
|
||||
<marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M2 1L8 5L2 9" fill="none" stroke="context-stroke"
|
||||
stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</marker>
|
||||
</defs>
|
||||
```
|
||||
|
||||
Use `marker-end="url(#arrow)"` on lines. The arrowhead inherits the line color via `context-stroke`.
|
||||
|
||||
### CSS Classes (Provided by the Template)
|
||||
|
||||
The template page provides:
|
||||
|
||||
- Text: `.t`, `.ts`, `.th`
|
||||
- Neutral: `.box`, `.arr`, `.leader`, `.node`
|
||||
- Color ramps: `.c-purple`, `.c-teal`, `.c-coral`, `.c-pink`, `.c-gray`, `.c-blue`, `.c-green`, `.c-amber`, `.c-red` (all with automatic light/dark mode)
|
||||
|
||||
You do **not** need to redefine these — just apply them in your SVG. The template file contains the full CSS definitions.
|
||||
|
||||
---
|
||||
|
||||
## SVG Boilerplate
|
||||
|
||||
Every SVG inside the template page starts with this exact structure:
|
||||
|
||||
```xml
|
||||
<svg width="100%" viewBox="0 0 680 {HEIGHT}" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5"
|
||||
markerWidth="6" markerHeight="6" orient="auto-start-reverse">
|
||||
<path d="M2 1L8 5L2 9" fill="none" stroke="context-stroke"
|
||||
stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- Diagram content here -->
|
||||
|
||||
</svg>
|
||||
```
|
||||
|
||||
Replace `{HEIGHT}` with the actual computed height (last element bottom + 40px).
|
||||
|
||||
### Node Patterns
|
||||
|
||||
**Single-line node (44px):**
|
||||
```xml
|
||||
<g class="node c-blue">
|
||||
<rect x="100" y="20" width="180" height="44" rx="8" stroke-width="0.5"/>
|
||||
<text class="th" x="190" y="42" text-anchor="middle" dominant-baseline="central">Service name</text>
|
||||
</g>
|
||||
```
|
||||
|
||||
**Two-line node (56px):**
|
||||
```xml
|
||||
<g class="node c-teal">
|
||||
<rect x="100" y="20" width="200" height="56" rx="8" stroke-width="0.5"/>
|
||||
<text class="th" x="200" y="38" text-anchor="middle" dominant-baseline="central">Service name</text>
|
||||
<text class="ts" x="200" y="56" text-anchor="middle" dominant-baseline="central">Short description</text>
|
||||
</g>
|
||||
```
|
||||
|
||||
**Connector (no label):**
|
||||
```xml
|
||||
<line x1="200" y1="76" x2="200" y2="120" class="arr" marker-end="url(#arrow)"/>
|
||||
```
|
||||
|
||||
**Container (dashed or solid):**
|
||||
```xml
|
||||
<g class="c-purple">
|
||||
<rect x="40" y="92" width="600" height="300" rx="16" stroke-width="0.5"/>
|
||||
<text class="th" x="66" y="116">Container label</text>
|
||||
<text class="ts" x="66" y="134">Subtitle info</text>
|
||||
</g>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Diagram Types
|
||||
|
||||
Choose the layout that fits the subject:
|
||||
|
||||
1. **Flowchart** — CI/CD pipelines, request lifecycles, approval workflows, data processing. Single-direction flow (top-down or left-right). Max 4-5 nodes per row.
|
||||
2. **Structural / Containment** — Cloud infrastructure nesting, system architecture with layers. Large outer containers with inner regions. Dashed rects for logical groupings.
|
||||
3. **API / Endpoint Map** — REST routes, GraphQL schemas. Tree from root, branching to resource groups, each containing endpoint nodes.
|
||||
4. **Microservice Topology** — Service mesh, event-driven systems. Services as nodes, arrows for communication patterns, message queues between.
|
||||
5. **Data Flow** — ETL pipelines, streaming architectures. Left-to-right flow from sources through processing to sinks.
|
||||
6. **Physical / Structural** — Vehicles, buildings, hardware, anatomy. Use shapes that match the physical form — `<path>` for curved bodies, `<polygon>` for tapered shapes, `<ellipse>`/`<circle>` for cylindrical parts, nested `<rect>` for compartments. See `references/physical-shape-cookbook.md`.
|
||||
7. **Infrastructure / Systems Integration** — Smart cities, IoT networks, multi-domain systems. Hub-spoke layout with central platform connecting subsystems. Semantic line styles (`.data-line`, `.power-line`, `.water-pipe`, `.road`). See `references/infrastructure-patterns.md`.
|
||||
8. **UI / Dashboard Mockups** — Admin panels, monitoring dashboards. Screen frame with nested chart/gauge/indicator elements. See `references/dashboard-patterns.md`.
|
||||
|
||||
For physical, infrastructure, and dashboard diagrams, load the matching reference file before generating — each one provides ready-made CSS classes and shape primitives.
|
||||
|
||||
---
|
||||
|
||||
## Validation Checklist
|
||||
|
||||
Before finalizing any SVG, verify ALL of the following:
|
||||
|
||||
1. Every `<text>` has class `t`, `ts`, or `th`.
|
||||
2. Every `<text>` inside a box has `dominant-baseline="central"`.
|
||||
3. Every connector `<path>` or `<line>` used as arrow has `fill="none"`.
|
||||
4. No arrow line crosses through an unrelated box.
|
||||
5. `box_width >= (longest_label_chars × 8) + 48` for 14px text.
|
||||
6. `box_width >= (longest_label_chars × 6.5) + 48` for 12px text.
|
||||
7. ViewBox height = bottom-most element + 40px.
|
||||
8. All content stays within x=40 to x=640.
|
||||
9. Color classes (`c-*`) are on `<g>` or shape elements, never on `<path>` connectors.
|
||||
10. Arrow `<defs>` block is present.
|
||||
11. No gradients, shadows, blur, or glow effects.
|
||||
12. Stroke width is 0.5px on all node borders.
|
||||
|
||||
---
|
||||
|
||||
## Output & Preview
|
||||
|
||||
### Default: standalone HTML file
|
||||
|
||||
Write a single `.html` file the user can open directly. No server, no dependencies, works offline. Pattern:
|
||||
|
||||
```python
|
||||
# 1. Load the template
|
||||
template = skill_view("concept-diagrams", "templates/template.html")
|
||||
|
||||
# 2. Fill in title, subtitle, and paste your SVG
|
||||
html = template.replace(
|
||||
"<!-- DIAGRAM TITLE HERE -->", "SN2 reaction mechanism"
|
||||
).replace(
|
||||
"<!-- OPTIONAL SUBTITLE HERE -->", "Bimolecular nucleophilic substitution"
|
||||
).replace(
|
||||
"<!-- PASTE SVG HERE -->", svg_content
|
||||
)
|
||||
|
||||
# 3. Write to a user-chosen path (or ./ by default)
|
||||
write_file("./sn2-mechanism.html", html)
|
||||
```
|
||||
|
||||
Tell the user how to open it:
|
||||
|
||||
```
|
||||
# macOS
|
||||
open ./sn2-mechanism.html
|
||||
# Linux
|
||||
xdg-open ./sn2-mechanism.html
|
||||
```
|
||||
|
||||
### Optional: local preview server (multi-diagram gallery)
|
||||
|
||||
Only use this when the user explicitly wants a browsable gallery of multiple diagrams.
|
||||
|
||||
**Rules:**
|
||||
- Bind to `127.0.0.1` only. Never `0.0.0.0`. Exposing diagrams on all network interfaces is a security hazard on shared networks.
|
||||
- Pick a free port (do NOT hard-code one) and tell the user the chosen URL.
|
||||
- The server is optional and opt-in — prefer the standalone HTML file first.
|
||||
|
||||
Recommended pattern (lets the OS pick a free ephemeral port):
|
||||
|
||||
```bash
|
||||
# Put each diagram in its own folder under .diagrams/
|
||||
mkdir -p .diagrams/sn2-mechanism
|
||||
# ...write .diagrams/sn2-mechanism/index.html...
|
||||
|
||||
# Serve on loopback only, free port
|
||||
cd .diagrams && python -c "
|
||||
import http.server, socketserver
|
||||
with socketserver.TCPServer(('127.0.0.1', 0), http.server.SimpleHTTPRequestHandler) as s:
|
||||
print(f'Serving at http://127.0.0.1:{s.server_address[1]}/')
|
||||
s.serve_forever()
|
||||
" &
|
||||
```
|
||||
|
||||
If the user insists on a fixed port, use `127.0.0.1:<port>` — still never `0.0.0.0`. Document how to stop the server (`kill %1` or `pkill -f "http.server"`).
|
||||
|
||||
---
|
||||
|
||||
## Examples Reference
|
||||
|
||||
The `examples/` directory ships 15 complete, tested diagrams. Browse them for working patterns before writing a new diagram of a similar type:
|
||||
|
||||
| File | Type | Demonstrates |
|
||||
|------|------|--------------|
|
||||
| `hospital-emergency-department-flow.md` | Flowchart | Priority routing with semantic colors |
|
||||
| `feature-film-production-pipeline.md` | Flowchart | Phased workflow, horizontal sub-flows |
|
||||
| `automated-password-reset-flow.md` | Flowchart | Auth flow with error branches |
|
||||
| `autonomous-llm-research-agent-flow.md` | Flowchart | Loop-back arrows, decision branches |
|
||||
| `place-order-uml-sequence.md` | Sequence | UML sequence diagram style |
|
||||
| `commercial-aircraft-structure.md` | Physical | Paths, polygons, ellipses for realistic shapes |
|
||||
| `wind-turbine-structure.md` | Physical cross-section | Underground/above-ground separation, color coding |
|
||||
| `smartphone-layer-anatomy.md` | Exploded view | Alternating left/right labels, layered components |
|
||||
| `apartment-floor-plan-conversion.md` | Floor plan | Walls, doors, proposed changes in dotted red |
|
||||
| `banana-journey-tree-to-smoothie.md` | Narrative journey | Winding path, progressive state changes |
|
||||
| `cpu-ooo-microarchitecture.md` | Hardware pipeline | Fan-out, memory hierarchy sidebar |
|
||||
| `sn2-reaction-mechanism.md` | Chemistry | Molecules, curved arrows, energy profile |
|
||||
| `smart-city-infrastructure.md` | Hub-spoke | Semantic line styles per system |
|
||||
| `electricity-grid-flow.md` | Multi-stage flow | Voltage hierarchy, flow markers |
|
||||
| `ml-benchmark-grouped-bar-chart.md` | Chart | Grouped bars, dual axis |
|
||||
|
||||
Load any example with:
|
||||
```
|
||||
skill_view(name="concept-diagrams", file_path="examples/<filename>")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference: What to Use When
|
||||
|
||||
| User says | Diagram type | Suggested colors |
|
||||
|-----------|--------------|------------------|
|
||||
| "show the pipeline" | Flowchart | gray start/end, purple steps, red errors, teal deploy |
|
||||
| "draw the data flow" | Data pipeline (left-right) | gray sources, purple processing, teal sinks |
|
||||
| "visualize the system" | Structural (containment) | purple container, teal services, coral data |
|
||||
| "map the endpoints" | API tree | purple root, one ramp per resource group |
|
||||
| "show the services" | Microservice topology | gray ingress, teal services, purple bus, coral workers |
|
||||
| "draw the aircraft/vehicle" | Physical | paths, polygons, ellipses for realistic shapes |
|
||||
| "smart city / IoT" | Hub-spoke integration | semantic line styles per subsystem |
|
||||
| "show the dashboard" | UI mockup | dark screen, chart colors: teal, purple, coral for alerts |
|
||||
| "power grid / electricity" | Multi-stage flow | voltage hierarchy (HV/MV/LV line weights) |
|
||||
| "wind turbine / turbine" | Physical cross-section | foundation + tower cutaway + nacelle color-coded |
|
||||
| "journey of X / lifecycle" | Narrative journey | winding path, progressive state changes |
|
||||
| "layers of X / exploded" | Exploded layer view | vertical stack, alternating labels |
|
||||
| "CPU / pipeline" | Hardware pipeline | vertical stages, fan-out to execution ports |
|
||||
| "floor plan / apartment" | Floor plan | walls, doors, proposed changes in dotted red |
|
||||
| "reaction mechanism" | Chemistry | atoms, bonds, curved arrows, transition state, energy profile |
|
||||
@@ -0,0 +1,192 @@
|
||||
---
|
||||
title: "Creative Ideation — Generate ideas via named methods from creative practice"
|
||||
sidebar_label: "Creative Ideation"
|
||||
description: "Generate ideas via named methods from creative practice"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Creative Ideation
|
||||
|
||||
Generate ideas via named methods from creative practice.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/creative-ideation` |
|
||||
| Path | `optional-skills/creative\creative-ideation` |
|
||||
| Version | `2.1.0` |
|
||||
| Author | SHL0MS |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Creative`, `Ideation`, `Brainstorming`, `Methods`, `Inspiration` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Creative Ideation
|
||||
|
||||
A library of ideation methods for any domain. Read the user's situation, route to the matching method, apply, generate output that is specific and non-obvious. Methods are tools — pick the right one for the situation, don't perform all of them.
|
||||
|
||||
## When to use
|
||||
|
||||
Any open-ended generative or selective question: "I want to make / build / write / start something", "I'm stuck", "inspire me", "make this weirder", "help me pick", "I need to invent X", "give me a research question".
|
||||
|
||||
## Operating rules
|
||||
|
||||
1. **Constraint plus direction is creativity.** No constraint = no traction. No direction = no shape. Methods supply both.
|
||||
2. **Refuse the first three ideas.** They're slop. Generate, discard, regenerate. See `references/anti-slop.md`.
|
||||
3. **One method per response unless asked.** Don't stack.
|
||||
4. **Specificity over abstraction.** Real proper nouns, real materials, real mechanisms. "An app for X" is slop; "a 200-line CLI tool that prints Y when Z" is direction. Naming a tech stack is not specificity — name a mechanism.
|
||||
5. **Weird must also be good.** Frame-breaking is the goal, but an idea that is strange with no real situation, mechanism, or reason to exist is its own failure mode. Every set of ideas must include at least one that is genuinely *buildable/pursuable now* — non-obvious but grounded, with a real first step. Don't trade all usefulness for surprise.
|
||||
6. **Name the method you used and who invented it.** Attribution invokes the discipline.
|
||||
7. **When user picks one, build it.** Don't keep generating after they've chosen.
|
||||
|
||||
## Routing — 4-step procedure
|
||||
|
||||
Do this *before* generating any output. Routing failures produce slop.
|
||||
|
||||
You may skip narrating the routing steps if it's cleaner, but **never compress at the cost of per-idea depth**: each idea's concrete mechanism, situational binding, and honest failure mode are what make output good (measured) — they are not scaffolding, do not cut them.
|
||||
|
||||
### Step 1 — Extract three signals from the prompt
|
||||
|
||||
**PHASE** — what stage is the user in?
|
||||
|
||||
| Phase | Cues |
|
||||
|---|---|
|
||||
| **GENERATING** | "give me an idea", "what should I make", "inspire me", no idea yet |
|
||||
| **EXPANDING** | "what else", "more like this", "give me variations" — has a base idea |
|
||||
| **SELECTING** | "help me pick", "which should I do", "I have these options" |
|
||||
| **UNBLOCKING** | "I'm stuck", "blocked", "going in circles", "stale" — has material |
|
||||
| **SUBVERTING** | "make it weirder", "less obvious", "this is too safe" |
|
||||
| **REFINING** | "this is fine but missing something", "feels rough" |
|
||||
| **SYNTHESIZING** | "I have a pile of notes / interviews / observations" |
|
||||
|
||||
**DOMAIN** — what is the user making/doing?
|
||||
|
||||
| Domain | Cues |
|
||||
|---|---|
|
||||
| **TEXT** | fiction, essay, poem, lyric, script, copy |
|
||||
| **OBJECT** | visual art, music, sound, performance, installation, sculpture |
|
||||
| **ARTIFACT** | software, hardware, mechanism, device |
|
||||
| **SYSTEM** | org, civic, institution, ecology, community |
|
||||
| **SELF** | life decision, career, personal practice |
|
||||
| **RESEARCH** | paper, thesis, scholarly question |
|
||||
| **PRODUCT** | business, market, service |
|
||||
|
||||
**SPECIFICITY** — how much constraint is in the prompt?
|
||||
|
||||
| Level | Cues |
|
||||
|---|---|
|
||||
| **NONE** | "I'm bored", "inspire me" — no domain, no project |
|
||||
| **DOMAIN** | "I want to write something" — knows the field, no project |
|
||||
| **PROJECT** | "I'm working on this specific X" |
|
||||
| **PROBLEM** | "I have this specific friction within X" |
|
||||
|
||||
### Step 2 — Apply overrides (highest priority, fire first)
|
||||
|
||||
Override rules beat the routing table:
|
||||
|
||||
- **Mood signal** — user says "weird", "strange", "surprising", "less obvious", "more interesting" → `references/methods/lateral-provocations.md` or `references/methods/pataphysics.md`, regardless of domain.
|
||||
- **User names a method** — use it.
|
||||
- **User asks for a method recommendation** ("which method") → surface 2–3 candidates with one-line each, ask which to apply. Don't silently default.
|
||||
- **High-slop terrain** — "AI ideas", "startup ideas", "habit tracker", "productivity / wellness / fitness / food / travel app" → force `references/methods/lateral-provocations.md` or `references/methods/pataphysics.md` over the obvious method. Refuse the first **5** ideas, not 3.
|
||||
|
||||
### Step 3 — Route by phase first, then domain
|
||||
|
||||
**By phase (applies regardless of domain):**
|
||||
|
||||
| Phase | Default route |
|
||||
|---|---|
|
||||
| GENERATING + SPECIFICITY=NONE | `references/full-prompt-library.md` **General** section (constraint dispatch) |
|
||||
| GENERATING + DOMAIN known | route by domain (next table) |
|
||||
| EXPANDING | `references/methods/scamper.md` |
|
||||
| SELECTING | `references/methods/premortem-and-inversion.md` (or `references/methods/compression-progress.md` for upside) |
|
||||
| UNBLOCKING | `references/methods/oblique-strategies.md` |
|
||||
| SUBVERTING | `references/methods/lateral-provocations.md` (fallback `references/methods/pataphysics.md`) |
|
||||
| REFINING (text) | `references/methods/defamiliarization.md` |
|
||||
| REFINING (other) | `references/methods/creative-discipline.md` (Tharp's spine) |
|
||||
| SYNTHESIZING | `references/methods/affinity-diagrams.md` |
|
||||
| Volume needed fast | `references/methods/volume-generation.md` |
|
||||
|
||||
**By domain (when GENERATING with DOMAIN known):**
|
||||
|
||||
| Domain | Default route |
|
||||
|---|---|
|
||||
| TEXT — formal / poetry | `references/methods/oulipo.md` |
|
||||
| TEXT — narrative | `references/methods/story-skeletons.md` |
|
||||
| TEXT — has source material to remix | `references/methods/chance-and-remix.md` |
|
||||
| OBJECT (music, visual, performance) | `references/methods/oblique-strategies.md` |
|
||||
| OBJECT — physical maker / wants a starting constraint | `references/full-prompt-library.md` **Physical / object** section |
|
||||
| ARTIFACT — wants a starting constraint | `references/full-prompt-library.md` **Software / artifact** section |
|
||||
| ARTIFACT — engineering invention with parameter conflict | `references/methods/triz-principles.md` |
|
||||
| ARTIFACT — software architecture | `references/methods/pattern-languages.md` |
|
||||
| ARTIFACT — has natural-system analog | `references/methods/biomimicry.md` |
|
||||
| ARTIFACT — accumulated assumptions to question | `references/methods/first-principles.md` |
|
||||
| SYSTEM (civic, org, institutional) | `references/methods/leverage-points.md` |
|
||||
| SYSTEM — collective / participatory | `references/full-prompt-library.md` **Social / collective** section |
|
||||
| SELF (life, career, what-to-study) | `references/methods/derive-and-mapping.md` |
|
||||
| RESEARCH — picking a question | `references/methods/compression-progress.md` |
|
||||
| RESEARCH — attacking a known problem | `references/methods/polya.md` |
|
||||
| PRODUCT (business, service) | `references/methods/jobs-to-be-done.md` |
|
||||
| Need to break a frame / find analogy | `references/methods/analogy-and-blending.md` |
|
||||
|
||||
### Step 4 — Handle ambiguity and contradiction
|
||||
|
||||
- **Multiple paths plausible** → pick the one closest to the user's actual phrasing. Don't pick the most interesting method to seem sophisticated.
|
||||
- **Genuinely ambiguous** → ask ONE clarifying question, don't silently guess. Examples: *"Are you generating ideas or picking between ones you have?"* / *"Is this for fiction, essay, or something else?"*
|
||||
- **Signals contradict** (e.g., "weird startup ideas" → product domain + weird mood) → **stack two methods explicitly**. State what you're doing: *"Using `jobs-to-be-done` for the product framing + `lateral-provocations` to break the obvious shape."*
|
||||
- **No match** → constraint dispatch (`references/full-prompt-library.md`) is the safe fallback.
|
||||
- **Same question asked again** → switch methods. Variation in method = variation in idea distribution.
|
||||
|
||||
### Anti-default check (run before generating)
|
||||
|
||||
- About to write "Here are 5 ideas:" or a bare numbered list? → STOP. Pick a method first.
|
||||
- About to default to generic LLM-mode brainstorming? → STOP. Pick a path above.
|
||||
- Output looks like what an unrouted LLM would produce? → routing failed, redo.
|
||||
|
||||
The default LLM mode is exactly what this skill exists to displace. If you generate without routing, you've defeated the skill.
|
||||
|
||||
For deeper edge cases (mood signals, stacking, anti-patterns) see `references/heuristics.md`.
|
||||
|
||||
## Output format
|
||||
|
||||
For the constraint-dispatch default path:
|
||||
|
||||
```
|
||||
## Constraint: [Name] — from [Source]
|
||||
> [The constraint, one sentence]
|
||||
|
||||
### Ideas
|
||||
|
||||
1. **[One-line pitch]**
|
||||
[2-3 sentences — what specifically is made, why it's interesting]
|
||||
⏱ [weekend/week/month] • 🔧 [stack/medium/materials]
|
||||
|
||||
2. ...
|
||||
3. ...
|
||||
```
|
||||
|
||||
For other methods, use the format the method specifies (TRIZ produces a contradiction analysis; OuLiPo produces constrained text; Oblique Strategies produces a single applied card → next move). Don't force every method into the constraint template.
|
||||
|
||||
**Every idea set, regardless of method:**
|
||||
- Name the method used. On slop terrain, name the obvious ideas you refused.
|
||||
- Give each idea its concrete mechanism and its honest failure mode / tradeoff / who-it's-for. This depth is what makes ideas land — measured, not decorative.
|
||||
- Mark at least one idea as the **grounded** one — buildable/pursuable now, non-obvious but with a real first step. The others can run further toward the strange; this one has to be genuinely doable. Don't let the whole set be weird-but-impractical.
|
||||
|
||||
## File map
|
||||
|
||||
- `references/full-prompt-library.md` — constraint library, sectioned by domain (General, Software, Physical, Social, Lists). Default path for SPECIFICITY=NONE.
|
||||
- `references/method-catalog.md` — one-line summary + when-to-use per method
|
||||
- `references/heuristics.md` — extended decision tree for edge cases
|
||||
- `references/anti-slop.md` — anti-slop rules; apply to every output
|
||||
- `references/exercises.md` — time-boxed exercises (5min / 30min / 1hr / day / week)
|
||||
- `references/methods/` — 22 named methods, one file each, load only the one you're using
|
||||
|
||||
## Attribution
|
||||
|
||||
Constraint-dispatch core adapted from [wttdotm.com/prompts.html](https://wttdotm.com/prompts.html). Methods drawn from primary sources cited in each method file.
|
||||
@@ -0,0 +1,169 @@
|
||||
---
|
||||
title: "Draw Your Font — Turn a handwriting photo into an installable TTF font"
|
||||
sidebar_label: "Draw Your Font"
|
||||
description: "Turn a handwriting photo into an installable TTF font"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Draw Your Font
|
||||
|
||||
Turn a handwriting photo into an installable TTF font.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/draw-your-font` |
|
||||
| Path | `optional-skills/creative\draw-your-font` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | Danilo Znamerovszkij (https://github.com/danilo-znamerovszkij/draw-your-font), ported by Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `font`, `handwriting`, `typography`, `ttf`, `woff`, `vision`, `creative` |
|
||||
| Related skills | [`pixel-art`](/docs/user-guide/skills/optional/creative/creative-pixel-art) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# draw-your-font
|
||||
|
||||
Photo of handwritten letters in → installable font out. You do the seeing
|
||||
(find and label letters, judge quality); the CLI does all geometry (trace,
|
||||
metrics, font assembly). Never edit SVG paths or coordinates yourself.
|
||||
|
||||
## Setup in Hermes (once per session)
|
||||
|
||||
The CLI is the pinned npm package `draw-your-font@0.1.0` — run it via npx (Node ≥ 18 required, no global install needed):
|
||||
|
||||
```bash
|
||||
npx -y draw-your-font@0.1.0 --help
|
||||
```
|
||||
|
||||
Wherever the examples below show `$DYF`, use `npx -y draw-your-font@0.1.0`. Shell variables do not persist between tool calls, so paste the full command each time. Everything runs locally; the user's handwriting never leaves the machine.
|
||||
|
||||
Photos arrive in Hermes either as a file path in the message or via the gateway image cache — use the actual file path with the CLI. When a photo lands in the conversation with no path, ask the user for the file (the CLI needs a real file, not your memory of the image).
|
||||
|
||||
Do the visual steps (contact sheets, previews, glyph sheets) by loading the PNGs with `vision_analyze`.
|
||||
|
||||
## Decide the flow
|
||||
|
||||
- **User has no photo yet** → offer the template: print, write, photograph.
|
||||
- **User shares photo(s) of handwriting** → main flow below.
|
||||
- **User pasted an image but there is no file path** → you can see it, but the
|
||||
CLI needs a file. Ask them to drag the image file into the terminal (that
|
||||
inserts its path) or give the path directly. Do not proceed from memory.
|
||||
- **User wants changes to a font built this session** → Refine section.
|
||||
|
||||
## Template flow (best quality)
|
||||
|
||||
```bash
|
||||
$DYF template -o template.pdf --charset minimal # or: spanish
|
||||
```
|
||||
|
||||
Tell the user: print it, write one character per box with a dark pen
|
||||
(0.5 mm+), keep the letter sitting on the solid line, then photograph each
|
||||
page from above in good light and share the file paths. The grid prints in
|
||||
light grey and vanishes during processing - only their ink survives.
|
||||
|
||||
## Main flow: photo(s) → font
|
||||
|
||||
**1. Segment.** Works for template pages and freeform photos alike:
|
||||
|
||||
```bash
|
||||
$DYF segment photo1.jpg photo2.jpg -d work
|
||||
```
|
||||
|
||||
**2. Look, then label.** Load `work/contact-1.png` with `vision_analyze` (one per photo): every
|
||||
detected blob is numbered. This is the step where your eyes matter - check:
|
||||
|
||||
- Did every written character get exactly one box? A letter drawn with
|
||||
separate strokes may appear as two boxes (relabel handles it: give the main
|
||||
box the character and mark the fragment `""`), and two touching letters may
|
||||
share one box (ask the user to re-shoot just those, or accept the gap).
|
||||
- Junk boxes (shadows, ruled lines, smudges, page edges) → label them `""`.
|
||||
|
||||
Then write `work/labels.json` mapping blob id → character, e.g.
|
||||
`{"0": "A", "1": "B", "7": "", "8": "a"}`:
|
||||
|
||||
- Template page: order is the charset order printed on the template - verify
|
||||
against the sheet instead of trusting it blindly. minimal order: A–Z, a–z,
|
||||
0–9, then `.,;:!?'"-()@#&+/$`; spanish appends `ÑñÁÉÍÓÚáéíóúü¿¡`.
|
||||
- Freeform: identify each letter from the contact sheet. Uppercase vs
|
||||
lowercase for shape-twins (S/s, O/o, C/c, X/x…) is decided by relative size
|
||||
and position - compare against neighbors you're sure of.
|
||||
- The user told you what they wrote (e.g. "ABC then abc")? Trust it, map in
|
||||
reading order (top row first, left to right), and verify visually.
|
||||
- Same letter appears twice → label the better-drawn one, `""` the other.
|
||||
|
||||
**3. Build.**
|
||||
|
||||
```bash
|
||||
$DYF build -d work --labels work/labels.json --name "Dan's Hand"
|
||||
```
|
||||
|
||||
Name the font after the user (ask if unclear - one short question max).
|
||||
|
||||
**4. Judge before delivering.** Load `work/preview.png` and `work/glyphs.png` with `vision_analyze`
|
||||
and critique like an art director:
|
||||
|
||||
- Broken or blotchy letters (bad trace) → often a faint pen stroke; try
|
||||
`--weight 1`, or ask for a re-shoot of just that letter.
|
||||
- Everything too thin/thick → rebuild with `--weight 1` / `--weight -1`.
|
||||
- Jagged edges → rebuild with `--smooth 1.5` (up to 2).
|
||||
- A letter placed wrong (e.g. a `g` not descending) → usually a mislabel;
|
||||
fix labels.json and rebuild.
|
||||
- Filled-in bowls (b, o, g look solid): should never happen - if it does,
|
||||
the crop is smudged; ask for a re-shoot.
|
||||
|
||||
Rebuilds are cheap and safe to iterate. Fix what you can yourself first;
|
||||
only bother the user for re-shoots when the source ink is the problem.
|
||||
|
||||
**5. Deliver.** The font lands at `<workdir>/<NameWithoutSpaces>.ttf` (the
|
||||
build output prints the exact path). Give that path and how to install:
|
||||
macOS - double-click → "Install Font"; Windows - right-click → "Install".
|
||||
Mention what's missing (the build prints uncovered letters) and offer,
|
||||
without pushing:
|
||||
|
||||
- Web formats + CSS: rebuild with `--formats ttf,woff,woff2,css`.
|
||||
- A legibility read (below).
|
||||
- Their next photo to fill missing characters: re-run segment with ALL
|
||||
photos (old and new) into a fresh workdir - `$DYF segment p1.jpg p2.jpg -d
|
||||
work2` - then relabel from the new contact sheets (blob ids renumber; the
|
||||
old labels.json does not carry over) and build from the new workdir.
|
||||
|
||||
## Refine (conversational iteration)
|
||||
|
||||
| User says | Do |
|
||||
|---|---|
|
||||
| "smoother / rounder" | `build … --smooth 1.5` (max 2) |
|
||||
| "thicker / bolder" | `build … --weight 1` (max 2) |
|
||||
| "thinner / lighter" | `build … --weight=-1` (negative needs the `=` form) |
|
||||
| "the g looks bad" | show them `work/crops/<id>.png` for that letter; offer re-shoot or smooth |
|
||||
| "wrong letter" / swap | edit labels.json, rebuild |
|
||||
| "give me woff2 / web" | `build … --formats ttf,woff,woff2,css` |
|
||||
| custom preview text | `$DYF preview -d work --text "…"` (after a build) |
|
||||
|
||||
All refine commands rebuild from the stored crops - no re-photographing
|
||||
needed unless the ink itself is the problem.
|
||||
|
||||
## Legibility report (offer after delivering)
|
||||
|
||||
```bash
|
||||
$DYF preview -d work --text "minimum mill rn m cl d I l 1 O 0 quick brown fox" -o work/legibility.png
|
||||
```
|
||||
|
||||
Read it and give an honest, kind read: a score out of 10 for body-text use,
|
||||
the 2–3 letter pairs most likely to confuse (rn→m, cl→d, I/l/1, O/0), and one
|
||||
or two concrete fixes (rewrite those letters larger, more spacing). Note that
|
||||
display use (headings, notes) is more forgiving than paragraphs. Never gate
|
||||
delivery on this - it's advice, not a blocker.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
Segmentation found far too many / too few blobs, grey guide lines surviving,
|
||||
shadow blobs, faint ballpoint strokes → see
|
||||
`references/troubleshooting.md`.
|
||||
@@ -0,0 +1,212 @@
|
||||
---
|
||||
title: "Excalidraw — Hand-drawn Excalidraw JSON diagrams (arch, flow, seq)"
|
||||
sidebar_label: "Excalidraw"
|
||||
description: "Hand-drawn Excalidraw JSON diagrams (arch, flow, seq)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Excalidraw
|
||||
|
||||
Hand-drawn Excalidraw JSON diagrams (arch, flow, seq).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/excalidraw` |
|
||||
| Path | `optional-skills/creative\excalidraw` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Excalidraw`, `Diagrams`, `Flowcharts`, `Architecture`, `Visualization`, `JSON` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Excalidraw Diagram Skill
|
||||
|
||||
Create diagrams by writing standard Excalidraw element JSON and saving as `.excalidraw` files. These files can be drag-and-dropped onto [excalidraw.com](https://excalidraw.com) for viewing and editing. No accounts, no API keys, no rendering libraries -- just JSON.
|
||||
|
||||
## When to use
|
||||
|
||||
Generate `.excalidraw` files for architecture diagrams, flowcharts, sequence diagrams, concept maps, and more. Files can be opened at excalidraw.com or uploaded for shareable links.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Load this skill** (you already did)
|
||||
2. **Write the elements JSON** -- an array of Excalidraw element objects
|
||||
3. **Save the file** using `write_file` to create a `.excalidraw` file
|
||||
4. **Optionally upload** for a shareable link using `scripts/upload.py` via `terminal`
|
||||
|
||||
### Saving a Diagram
|
||||
|
||||
Wrap your elements array in the standard `.excalidraw` envelope and save with `write_file`:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "excalidraw",
|
||||
"version": 2,
|
||||
"source": "hermes-agent",
|
||||
"elements": [ ...your elements array here... ],
|
||||
"appState": {
|
||||
"viewBackgroundColor": "#ffffff"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Save to any path, e.g. `~/diagrams/my_diagram.excalidraw`.
|
||||
|
||||
### Uploading for a Shareable Link
|
||||
|
||||
Run the upload script (located in this skill's `scripts/` directory) via terminal:
|
||||
|
||||
```bash
|
||||
python skills/creative/excalidraw/scripts/upload.py ~/diagrams/my_diagram.excalidraw
|
||||
```
|
||||
|
||||
This uploads to excalidraw.com (no account needed) and prints a shareable URL. Requires the `cryptography` pip package (`pip install cryptography`).
|
||||
|
||||
---
|
||||
|
||||
## Element Format Reference
|
||||
|
||||
### Required Fields (all elements)
|
||||
`type`, `id` (unique string), `x`, `y`, `width`, `height`
|
||||
|
||||
### Defaults (skip these -- they're applied automatically)
|
||||
- `strokeColor`: `"#1e1e1e"`
|
||||
- `backgroundColor`: `"transparent"`
|
||||
- `fillStyle`: `"solid"`
|
||||
- `strokeWidth`: `2`
|
||||
- `roughness`: `1` (hand-drawn look)
|
||||
- `opacity`: `100`
|
||||
|
||||
Canvas background is white.
|
||||
|
||||
### Element Types
|
||||
|
||||
**Rectangle**:
|
||||
```json
|
||||
{ "type": "rectangle", "id": "r1", "x": 100, "y": 100, "width": 200, "height": 100 }
|
||||
```
|
||||
- `roundness: { "type": 3 }` for rounded corners
|
||||
- `backgroundColor: "#a5d8ff"`, `fillStyle: "solid"` for filled
|
||||
|
||||
**Ellipse**:
|
||||
```json
|
||||
{ "type": "ellipse", "id": "e1", "x": 100, "y": 100, "width": 150, "height": 150 }
|
||||
```
|
||||
|
||||
**Diamond**:
|
||||
```json
|
||||
{ "type": "diamond", "id": "d1", "x": 100, "y": 100, "width": 150, "height": 150 }
|
||||
```
|
||||
|
||||
**Labeled shape (container binding)** -- create a text element bound to the shape:
|
||||
|
||||
> **WARNING:** Do NOT use `"label": { "text": "..." }` on shapes. This is NOT a valid
|
||||
> Excalidraw property and will be silently ignored, producing blank shapes. You MUST
|
||||
> use the container binding approach below.
|
||||
|
||||
The shape needs `boundElements` listing the text, and the text needs `containerId` pointing back:
|
||||
```json
|
||||
{ "type": "rectangle", "id": "r1", "x": 100, "y": 100, "width": 200, "height": 80,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"boundElements": [{ "id": "t_r1", "type": "text" }] },
|
||||
{ "type": "text", "id": "t_r1", "x": 105, "y": 110, "width": 190, "height": 25,
|
||||
"text": "Hello", "fontSize": 20, "fontFamily": 1, "strokeColor": "#1e1e1e",
|
||||
"textAlign": "center", "verticalAlign": "middle",
|
||||
"containerId": "r1", "originalText": "Hello", "autoResize": true }
|
||||
```
|
||||
- Works on rectangle, ellipse, diamond
|
||||
- Text is auto-centered by Excalidraw when `containerId` is set
|
||||
- The text `x`/`y`/`width`/`height` are approximate -- Excalidraw recalculates them on load
|
||||
- `originalText` should match `text`
|
||||
- Always include `fontFamily: 1` (Virgil/hand-drawn font)
|
||||
|
||||
**Labeled arrow** -- same container binding approach:
|
||||
```json
|
||||
{ "type": "arrow", "id": "a1", "x": 300, "y": 150, "width": 200, "height": 0,
|
||||
"points": [[0,0],[200,0]], "endArrowhead": "arrow",
|
||||
"boundElements": [{ "id": "t_a1", "type": "text" }] },
|
||||
{ "type": "text", "id": "t_a1", "x": 370, "y": 130, "width": 60, "height": 20,
|
||||
"text": "connects", "fontSize": 16, "fontFamily": 1, "strokeColor": "#1e1e1e",
|
||||
"textAlign": "center", "verticalAlign": "middle",
|
||||
"containerId": "a1", "originalText": "connects", "autoResize": true }
|
||||
```
|
||||
|
||||
**Standalone text** (titles and annotations only -- no container):
|
||||
```json
|
||||
{ "type": "text", "id": "t1", "x": 150, "y": 138, "text": "Hello", "fontSize": 20,
|
||||
"fontFamily": 1, "strokeColor": "#1e1e1e", "originalText": "Hello", "autoResize": true }
|
||||
```
|
||||
- `x` is the LEFT edge. To center at position `cx`: `x = cx - (text.length * fontSize * 0.5) / 2`
|
||||
- Do NOT rely on `textAlign` or `width` for positioning
|
||||
|
||||
**Arrow**:
|
||||
```json
|
||||
{ "type": "arrow", "id": "a1", "x": 300, "y": 150, "width": 200, "height": 0,
|
||||
"points": [[0,0],[200,0]], "endArrowhead": "arrow" }
|
||||
```
|
||||
- `points`: `[dx, dy]` offsets from element `x`, `y`
|
||||
- `endArrowhead`: `null` | `"arrow"` | `"bar"` | `"dot"` | `"triangle"`
|
||||
- `strokeStyle`: `"solid"` (default) | `"dashed"` | `"dotted"`
|
||||
|
||||
### Arrow Bindings (connect arrows to shapes)
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "arrow", "id": "a1", "x": 300, "y": 150, "width": 150, "height": 0,
|
||||
"points": [[0,0],[150,0]], "endArrowhead": "arrow",
|
||||
"startBinding": { "elementId": "r1", "fixedPoint": [1, 0.5] },
|
||||
"endBinding": { "elementId": "r2", "fixedPoint": [0, 0.5] }
|
||||
}
|
||||
```
|
||||
|
||||
`fixedPoint` coordinates: `top=[0.5,0]`, `bottom=[0.5,1]`, `left=[0,0.5]`, `right=[1,0.5]`
|
||||
|
||||
### Drawing Order (z-order)
|
||||
- Array order = z-order (first = back, last = front)
|
||||
- Emit progressively: background zones → shape → its bound text → its arrows → next shape
|
||||
- BAD: all rectangles, then all texts, then all arrows
|
||||
- GOOD: bg_zone → shape1 → text_for_shape1 → arrow1 → arrow_label_text → shape2 → text_for_shape2 → ...
|
||||
- Always place the bound text element immediately after its container shape
|
||||
|
||||
### Sizing Guidelines
|
||||
|
||||
**Font sizes:**
|
||||
- Minimum `fontSize`: **16** for body text, labels, descriptions
|
||||
- Minimum `fontSize`: **20** for titles and headings
|
||||
- Minimum `fontSize`: **14** for secondary annotations only (sparingly)
|
||||
- NEVER use `fontSize` below 14
|
||||
|
||||
**Element sizes:**
|
||||
- Minimum shape size: 120x60 for labeled rectangles/ellipses
|
||||
- Leave 20-30px gaps between elements minimum
|
||||
- Prefer fewer, larger elements over many tiny ones
|
||||
|
||||
### Color Palette
|
||||
|
||||
See `references/colors.md` for full color tables. Quick reference:
|
||||
|
||||
| Use | Fill Color | Hex |
|
||||
|-----|-----------|-----|
|
||||
| Primary / Input | Light Blue | `#a5d8ff` |
|
||||
| Success / Output | Light Green | `#b2f2bb` |
|
||||
| Warning / External | Light Orange | `#ffd8a8` |
|
||||
| Processing / Special | Light Purple | `#d0bfff` |
|
||||
| Error / Critical | Light Red | `#ffc9c9` |
|
||||
| Notes / Decisions | Light Yellow | `#fff3bf` |
|
||||
| Storage / Data | Light Teal | `#c3fae8` |
|
||||
|
||||
### Tips
|
||||
- Use the color palette consistently across the diagram
|
||||
- **Text contrast is CRITICAL** -- never use light gray on white backgrounds. Minimum text color on white: `#757575`
|
||||
- Do NOT use emoji in text -- they don't render in Excalidraw's font
|
||||
- For dark mode diagrams, see `references/dark-mode.md`
|
||||
- For larger examples, see `references/examples.md`
|
||||
@@ -0,0 +1,191 @@
|
||||
---
|
||||
title: "Heartmula — HeartMuLa: Suno-like song generation from lyrics + tags"
|
||||
sidebar_label: "Heartmula"
|
||||
description: "HeartMuLa: Suno-like song generation from lyrics + tags"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Heartmula
|
||||
|
||||
HeartMuLa: Suno-like song generation from lyrics + tags.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/heartmula` |
|
||||
| Path | `optional-skills/creative\heartmula` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Teknium (teknium1), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `music`, `audio`, `generation`, `ai`, `heartmula`, `heartcodec`, `lyrics`, `songs` |
|
||||
| Related skills | [`audiocraft-audio-generation`](/docs/user-guide/skills/optional/creative/creative-audiocraft-audio-generation), [`songwriting-and-ai-music`](/docs/user-guide/skills/bundled/creative/creative-songwriting-and-ai-music) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# HeartMuLa - Open-Source Music Generation
|
||||
|
||||
## Overview
|
||||
HeartMuLa is a family of open-source music foundation models (Apache-2.0) that generates music conditioned on lyrics and tags, with multilingual support. Generates full songs from lyrics + tags. Comparable to Suno for open-source. Includes:
|
||||
- **HeartMuLa** - Music language model (3B/7B) for generation from lyrics + tags
|
||||
- **HeartCodec** - 12.5Hz music codec for high-fidelity audio reconstruction
|
||||
- **HeartTranscriptor** - Whisper-based lyrics transcription
|
||||
- **HeartCLAP** - Audio-text alignment model
|
||||
|
||||
## When to Use
|
||||
- User wants to generate music/songs from text descriptions
|
||||
- User wants an open-source Suno alternative
|
||||
- User wants local/offline music generation
|
||||
- User asks about HeartMuLa, heartlib, or AI music generation
|
||||
|
||||
## Hardware Requirements
|
||||
- **Minimum**: 8GB VRAM with `--lazy_load true` (loads/unloads models sequentially)
|
||||
- **Recommended**: 16GB+ VRAM for comfortable single-GPU usage
|
||||
- **Multi-GPU**: Use `--mula_device cuda:0 --codec_device cuda:1` to split across GPUs
|
||||
- 3B model with lazy_load peaks at ~6.2GB VRAM
|
||||
|
||||
## Installation Steps
|
||||
|
||||
### 1. Clone Repository
|
||||
```bash
|
||||
cd ~/ # or desired directory
|
||||
git clone https://github.com/HeartMuLa/heartlib.git
|
||||
cd heartlib
|
||||
```
|
||||
|
||||
### 2. Create Virtual Environment (Python 3.10 required)
|
||||
```bash
|
||||
uv venv --python 3.10 .venv
|
||||
. .venv/bin/activate
|
||||
uv pip install -e .
|
||||
```
|
||||
|
||||
### 3. Fix Dependency Compatibility Issues
|
||||
|
||||
**IMPORTANT**: As of Feb 2026, the pinned dependencies have conflicts with newer packages. Apply these fixes:
|
||||
|
||||
```bash
|
||||
# Upgrade datasets (old version incompatible with current pyarrow)
|
||||
uv pip install --upgrade datasets
|
||||
|
||||
# Upgrade transformers (needed for huggingface-hub 1.x compatibility)
|
||||
uv pip install --upgrade transformers
|
||||
```
|
||||
|
||||
### 4. Patch Source Code (Required for transformers 5.x)
|
||||
|
||||
**Patch 1 - RoPE cache fix** in `src/heartlib/heartmula/modeling_heartmula.py`:
|
||||
|
||||
In the `setup_caches` method of the `HeartMuLa` class, add RoPE reinitialization after the `reset_caches` try/except block and before the `with device:` block:
|
||||
|
||||
```python
|
||||
# Re-initialize RoPE caches that were skipped during meta-device loading
|
||||
from torchtune.models.llama3_1._position_embeddings import Llama3ScaledRoPE
|
||||
for module in self.modules():
|
||||
if isinstance(module, Llama3ScaledRoPE) and not module.is_cache_built:
|
||||
module.rope_init()
|
||||
module.to(device)
|
||||
```
|
||||
|
||||
**Why**: `from_pretrained` creates model on meta device first; `Llama3ScaledRoPE.rope_init()` skips cache building on meta tensors, then never rebuilds after weights are loaded to real device.
|
||||
|
||||
**Patch 2 - HeartCodec loading fix** in `src/heartlib/pipelines/music_generation.py`:
|
||||
|
||||
Add `ignore_mismatched_sizes=True` to ALL `HeartCodec.from_pretrained()` calls (there are 2: the eager load in `__init__` and the lazy load in the `codec` property).
|
||||
|
||||
**Why**: VQ codebook `initted` buffers have shape `[1]` in checkpoint vs `[]` in model. Same data, just scalar vs 0-d tensor. Safe to ignore.
|
||||
|
||||
### 5. Download Model Checkpoints
|
||||
```bash
|
||||
cd heartlib # project root
|
||||
hf download --local-dir './ckpt' 'HeartMuLa/HeartMuLaGen'
|
||||
hf download --local-dir './ckpt/HeartMuLa-oss-3B' 'HeartMuLa/HeartMuLa-oss-3B-happy-new-year'
|
||||
hf download --local-dir './ckpt/HeartCodec-oss' 'HeartMuLa/HeartCodec-oss-20260123'
|
||||
```
|
||||
|
||||
All 3 can be downloaded in parallel. Total size is several GB.
|
||||
|
||||
## GPU / CUDA
|
||||
|
||||
HeartMuLa uses CUDA by default (`--mula_device cuda --codec_device cuda`). No extra setup needed if the user has an NVIDIA GPU with PyTorch CUDA support installed.
|
||||
|
||||
- The installed `torch==2.4.1` includes CUDA 12.1 support out of the box
|
||||
- `torchtune` may report version `0.4.0+cpu` — this is just package metadata, it still uses CUDA via PyTorch
|
||||
- To verify GPU is being used, look for "CUDA memory" lines in the output (e.g. "CUDA memory before unloading: 6.20 GB")
|
||||
- **No GPU?** You can run on CPU with `--mula_device cpu --codec_device cpu`, but expect generation to be **extremely slow** (potentially 30-60+ minutes for a single song vs ~4 minutes on GPU). CPU mode also requires significant RAM (~12GB+ free). If the user has no NVIDIA GPU, recommend using a cloud GPU service (Google Colab free tier with T4, Lambda Labs, etc.) or the online demo at https://heartmula.github.io/ instead.
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Generation
|
||||
```bash
|
||||
cd heartlib
|
||||
. .venv/bin/activate
|
||||
python ./examples/run_music_generation.py \
|
||||
--model_path=./ckpt \
|
||||
--version="3B" \
|
||||
--lyrics="./assets/lyrics.txt" \
|
||||
--tags="./assets/tags.txt" \
|
||||
--save_path="./assets/output.mp3" \
|
||||
--lazy_load true
|
||||
```
|
||||
|
||||
### Input Formatting
|
||||
|
||||
**Tags** (comma-separated, no spaces):
|
||||
```
|
||||
piano,happy,wedding,synthesizer,romantic
|
||||
```
|
||||
or
|
||||
```
|
||||
rock,energetic,guitar,drums,male-vocal
|
||||
```
|
||||
|
||||
**Lyrics** (use bracketed structural tags):
|
||||
```
|
||||
[Intro]
|
||||
|
||||
[Verse]
|
||||
Your lyrics here...
|
||||
|
||||
[Chorus]
|
||||
Chorus lyrics...
|
||||
|
||||
[Bridge]
|
||||
Bridge lyrics...
|
||||
|
||||
[Outro]
|
||||
```
|
||||
|
||||
### Key Parameters
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `--max_audio_length_ms` | 240000 | Max length in ms (240s = 4 min) |
|
||||
| `--topk` | 50 | Top-k sampling |
|
||||
| `--temperature` | 1.0 | Sampling temperature |
|
||||
| `--cfg_scale` | 1.5 | Classifier-free guidance scale |
|
||||
| `--lazy_load` | false | Load/unload models on demand (saves VRAM) |
|
||||
| `--mula_dtype` | bfloat16 | Dtype for HeartMuLa (bf16 recommended) |
|
||||
| `--codec_dtype` | float32 | Dtype for HeartCodec (fp32 recommended for quality) |
|
||||
|
||||
### Performance
|
||||
- RTF (Real-Time Factor) ≈ 1.0 — a 4-minute song takes ~4 minutes to generate
|
||||
- Output: MP3, 48kHz stereo, 128kbps
|
||||
|
||||
## Pitfalls
|
||||
1. **Do NOT use bf16 for HeartCodec** — degrades audio quality. Use fp32 (default).
|
||||
2. **Tags may be ignored** — known issue (#90). Lyrics tend to dominate; experiment with tag ordering.
|
||||
3. **Triton not available on macOS** — Linux/CUDA only for GPU acceleration.
|
||||
4. **RTX 5080 incompatibility** reported in upstream issues.
|
||||
5. The dependency pin conflicts require the manual upgrades and patches described above.
|
||||
|
||||
## Links
|
||||
- Repo: https://github.com/HeartMuLa/heartlib
|
||||
- Models: https://huggingface.co/HeartMuLa
|
||||
- Paper: https://arxiv.org/abs/2601.10547
|
||||
- License: Apache-2.0
|
||||
@@ -0,0 +1,222 @@
|
||||
---
|
||||
title: "Hyperframes — Render MP4/WebM videos from HTML compositions"
|
||||
sidebar_label: "Hyperframes"
|
||||
description: "Render MP4/WebM videos from HTML compositions"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Hyperframes
|
||||
|
||||
Render MP4/WebM videos from HTML compositions.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/hyperframes` |
|
||||
| Path | `optional-skills/creative\hyperframes` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | heygen-com |
|
||||
| License | Apache-2.0 |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `creative`, `video`, `animation`, `html`, `gsap`, `motion-graphics` |
|
||||
| Related skills | [`manim-video`](/docs/user-guide/skills/bundled/creative/creative-manim-video), [`meme-generation`](/docs/user-guide/skills/optional/creative/creative-meme-generation) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# HyperFrames
|
||||
|
||||
HTML is the source of truth for video. A composition is an HTML file with `data-*` attributes for timing, a GSAP timeline for animation, and CSS for appearance. The HyperFrames engine captures the page frame-by-frame and encodes to MP4/WebM with FFmpeg.
|
||||
|
||||
**Complement to `manim-video`:** Use `manim-video` for mathematical/geometric explainers (equations, 3B1B-style). Use `hyperframes` for motion-graphics, talking-head with captions, product tours, social overlays, shader transitions, and anything driven by real video/audio media.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks for a rendered video from text, a script, or a website
|
||||
- Animated title cards, lower thirds, or typographic intros
|
||||
- Captioned narration video (TTS + captions synced to waveform)
|
||||
- Audio-reactive visuals (beat sync, spectrum bars, pulsing glow)
|
||||
- Scene-to-scene transitions (crossfade, wipe, shader warp, flash-through-white)
|
||||
- Social overlays (Instagram/TikTok/YouTube style)
|
||||
- Website-to-video pipeline (capture a URL, produce a promo)
|
||||
- Any HTML/CSS/JS animation that must render deterministically to a video file
|
||||
|
||||
Do **not** use this skill for:
|
||||
- Pure math/equation animation (→ `manim-video`)
|
||||
- Image generation or memes (→ `meme-generation`, image models)
|
||||
- Live video conferencing or streaming
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
npx hyperframes init my-video # scaffold a project
|
||||
cd my-video
|
||||
npx hyperframes lint # validate before preview/render
|
||||
npx hyperframes preview # live-reload preview (long-lived server, port 3002)
|
||||
npx hyperframes render --output final.mp4 # render to MP4
|
||||
npx hyperframes doctor # diagnose environment issues
|
||||
```
|
||||
|
||||
`preview` is a **long-lived** Next.js server that holds Chrome render workers open. Always stop it when done (see [Cleanup](#cleanup)) — a forgotten preview keeps idle `chrome-headless-shell` workers alive that, on GPU-less hosts (WSL, containers, CI), spin a CPU core each indefinitely via software WebGL (swiftshader).
|
||||
|
||||
Render flags: `--quality draft|standard|high` · `--fps 24|30|60` · `--format mp4|webm` · `--docker` (reproducible) · `--strict`.
|
||||
|
||||
Full CLI reference: [references/cli.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/cli.md).
|
||||
|
||||
## Setup (one-time)
|
||||
|
||||
```bash
|
||||
bash "$(dirname "$(find ~/.hermes/skills -path '*/hyperframes/SKILL.md' 2>/dev/null | head -1)")/scripts/setup.sh"
|
||||
```
|
||||
|
||||
The script:
|
||||
1. Verifies Node.js >= 22 and FFmpeg are installed (prints fix instructions if not).
|
||||
2. Installs the `hyperframes` CLI globally (`npm install -g hyperframes@>=0.4.2`).
|
||||
3. Pre-caches `chrome-headless-shell` via Puppeteer — **required** for best-quality rendering via Chrome's `HeadlessExperimental.beginFrame` capture path.
|
||||
4. Runs `npx hyperframes doctor` and reports the result.
|
||||
|
||||
See [references/troubleshooting.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/troubleshooting.md) if setup fails.
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Plan before writing HTML
|
||||
|
||||
Before touching code, articulate at a high level:
|
||||
- **What** — narrative arc, key moments, emotional beats
|
||||
- **Structure** — compositions, tracks (video/audio/overlays), durations
|
||||
- **Visual identity** — colors, fonts, motion character (explosive / cinematic / fluid / technical)
|
||||
- **Hero frame** — for each scene, the moment when the most elements are simultaneously visible. This is the static layout you'll build first.
|
||||
|
||||
**Visual Identity Gate (HARD-GATE).** Before writing ANY composition HTML, a visual identity must be defined. Do NOT write compositions with default or generic colors (`#333`, `#3b82f6`, `Roboto` are tells that this step was skipped). Check in order:
|
||||
|
||||
1. **`DESIGN.md` at project root?** → Use its exact colors, fonts, motion rules, and "What NOT to Do" constraints.
|
||||
2. **User named a style** (e.g. "Swiss Pulse", "dark and techy", "luxury brand")? → Generate a minimal `DESIGN.md` with `## Style Prompt`, `## Colors` (3-5 hex with roles), `## Typography` (1-2 families), `## What NOT to Do` (3-5 anti-patterns).
|
||||
3. **None of the above?** → Ask 3 questions before writing any HTML:
|
||||
- Mood? (explosive / cinematic / fluid / technical / chaotic / warm)
|
||||
- Light or dark canvas?
|
||||
- Any brand colors, fonts, or visual references?
|
||||
|
||||
Then generate a `DESIGN.md` from the answers. Every composition must trace its palette and typography back to `DESIGN.md` or explicit user direction.
|
||||
|
||||
### 2. Scaffold
|
||||
|
||||
```bash
|
||||
npx hyperframes init my-video --non-interactive
|
||||
```
|
||||
|
||||
Templates: `blank`, `warm-grain`, `play-mode`, `swiss-grid`, `vignelli`, `decision-tree`, `kinetic-type`, `product-promo`, `nyt-graph`. Pass `--example <name>` to pick one, `--video clip.mp4` or `--audio track.mp3` to seed with media.
|
||||
|
||||
### 3. Layout before animation
|
||||
|
||||
Write the static HTML+CSS for the **hero frame first** — no GSAP yet. The `.scene-content` container must fill the scene (`width:100%; height:100%; padding:Npx`) with `display:flex` + `gap`. Use padding to push content inward — never `position: absolute; top: Npx` on a content container (content overflows when taller than the remaining space).
|
||||
|
||||
Only after the hero frame looks right, add `gsap.from()` entrances (animate **to** the CSS position) and `gsap.to()` exits (animate **from** it).
|
||||
|
||||
See [references/composition.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/composition.md) for the full data-attribute schema and composition rules.
|
||||
|
||||
### 4. Animate with GSAP
|
||||
|
||||
Every composition must:
|
||||
- Register its timeline: `window.__timelines["<composition-id>"] = tl`
|
||||
- Start paused: `gsap.timeline({ paused: true })` — the player controls playback
|
||||
- Use finite `repeat` values (no `repeat: -1` — breaks the capture engine). Calculate: `repeat: Math.ceil(duration / cycleDuration) - 1`.
|
||||
- Be deterministic — no `Math.random()`, `Date.now()`, or wall-clock logic. Use a seeded PRNG if you need pseudo-randomness.
|
||||
- Build synchronously — no `async`/`await`, `setTimeout`, or Promises around timeline construction.
|
||||
|
||||
See [references/gsap.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/gsap.md) for the core GSAP API (tweens, eases, stagger, timelines).
|
||||
|
||||
### 5. Transitions between scenes
|
||||
|
||||
Multi-scene compositions require transitions. Rules:
|
||||
1. **Always use a transition between scenes** — no jump cuts.
|
||||
2. **Always use entrance animations** on every scene element (`gsap.from(...)`).
|
||||
3. **Never use exit animations** except on the final scene — the transition IS the exit.
|
||||
4. The final scene may fade out.
|
||||
|
||||
Use `npx hyperframes add <transition-name>` to install shader transitions (`flash-through-white`, `liquid-wipe`, etc.). Full list: `npx hyperframes add --list`.
|
||||
|
||||
### 6. Audio, captions, TTS, audio-reactive, highlighting
|
||||
|
||||
- **Audio:** always a separate `<audio>` element (video is `muted playsinline`).
|
||||
- **TTS:** `npx hyperframes tts "Script text" --voice af_nova --output narration.wav`. List voices with `--list`. Voice ID first letter encodes language (`a`/`b`=English, `e`=Spanish, `f`=French, `j`=Japanese, `z`=Mandarin, etc.) — the CLI auto-infers the phonemizer locale; pass `--lang` only to override. Non-English phonemization requires `espeak-ng` installed system-wide.
|
||||
- **Captions:** `npx hyperframes transcribe narration.wav` → word-level transcript. Pick style from the transcript tone (hype / corporate / tutorial / storytelling / social — see the table in `references/features.md`). **Language rule:** never use `.en` whisper models unless the audio is confirmed English — `.en` translates non-English audio instead of transcribing it. Every caption group MUST have a hard `tl.set(el, { opacity: 0, visibility: "hidden" }, group.end)` kill after its exit tween — otherwise groups leak visible into later ones.
|
||||
- **Audio-reactive visuals:** pre-extract audio bands (bass / mid / treble) and sample per-frame inside the timeline with a `for` loop of `tl.call(draw, [], f / fps)` — a single long tween does NOT react to audio. Map bass → `scale` (pulse), treble → `textShadow`/`boxShadow` (glow), overall amplitude → `opacity`/`y`/`backgroundColor`. Avoid equalizer-bar clichés — let content guide the visual, audio drive its behavior.
|
||||
- **Marker-style highlighting:** highlight, circle, burst, scribble, sketchout effects for text emphasis are deterministic CSS+GSAP — see `references/features.md#marker-highlighting`. Fully seekable, no animated SVG filters.
|
||||
- **Scene transitions:** every multi-scene composition MUST use transitions (no jump cuts). Pick from CSS primitives (push slide, blur crossfade, zoom through, staggered blocks) or shader transitions (`flash-through-white`, `liquid-wipe`, `cross-warp-morph`, `chromatic-split`, etc.) via `npx hyperframes add`. Mood and energy tables live in `references/features.md#transitions`. Do not mix CSS and shader transitions in the same composition.
|
||||
|
||||
### 7. Lint, validate, inspect, preview, render
|
||||
|
||||
```bash
|
||||
npx hyperframes lint # catches missing data-composition-id, overlapping tracks, unregistered timelines
|
||||
npx hyperframes validate # WCAG contrast audit at 5 timestamps
|
||||
npx hyperframes inspect # visual layout audit — overflow, off-frame elements, occluded text
|
||||
npx hyperframes preview # live browser preview
|
||||
npx hyperframes render --quality draft --output draft.mp4 # fast iteration
|
||||
npx hyperframes render --quality high --output final.mp4 # final delivery
|
||||
```
|
||||
|
||||
`hyperframes validate` samples background pixels behind every text element and warns on contrast ratios below 4.5:1 (or 3:1 for large text). `hyperframes inspect` is the layout-side companion — runs the page at multiple timestamps and flags issues that a static lint can't see (a caption that wraps past the safe area only at 4.5s, a card that overflows when its title is the longest variant, an element that ends up behind a transition shader). Run `inspect` especially on compositions with speech bubbles, cards, captions, or tight typography.
|
||||
|
||||
### 8. Website-to-video (if the user gives a URL)
|
||||
|
||||
Use the 7-step capture-to-video workflow in [references/website-to-video.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/website-to-video.md): capture → DESIGN.md → SCRIPT.md → storyboard → composition → render → deliver.
|
||||
|
||||
## Cleanup
|
||||
|
||||
`render` is one-shot (workers exit when it finishes). `preview` is **not** — it runs a background Next.js server that keeps Chrome workers resident until you stop it. Never leave one running: on GPU-less hosts each idle worker's swiftshader process pegs a CPU core, and a preview left open for days stacks up multiple.
|
||||
|
||||
Stop a preview when the user is done reviewing (or before starting a new one):
|
||||
|
||||
```bash
|
||||
pkill -f "hyperframes.*preview" # the Studio server (frees port 3002)
|
||||
pkill -f chrome-headless-shell # its render workers; only safe if nothing else uses them
|
||||
```
|
||||
|
||||
If unsure whether other tools use `chrome-headless-shell`, check first: `pgrep -af chrome-headless-shell`. Recover a wedged host (many idle workers spinning CPU) the same way — see [references/troubleshooting.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/troubleshooting.md#runaway-cpu-from-leftover-preview-workers).
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **Leaving `preview` running** — it's a long-lived server holding Chrome workers; on WSL/containers/CI those idle workers spin a CPU core each (software WebGL). Stop it when done — see [Cleanup](#cleanup).
|
||||
|
||||
- **`HeadlessExperimental.beginFrame' wasn't found`** — Chromium 147+ removed this protocol. Ensure you're on `hyperframes@>=0.4.2` (auto-detects and falls back to screenshot mode). Escape hatch: `export PRODUCER_FORCE_SCREENSHOT=true`. See [hyperframes#294](https://github.com/heygen-com/hyperframes/issues/294) and [references/troubleshooting.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/troubleshooting.md).
|
||||
- **System Chrome (not `chrome-headless-shell`)** — renders hang for 120s then timeout. Run `npx puppeteer browsers install chrome-headless-shell` (setup.sh does this). `hyperframes doctor` reports which binary will be used.
|
||||
- **`repeat: -1` anywhere** — breaks the capture engine. Always compute a finite repeat count.
|
||||
- **`gsap.set()` on clip elements that enter later** — the element doesn't exist at page load. Use `tl.set(selector, vars, timePosition)` inside the timeline instead, at or after the clip's `data-start`.
|
||||
- **`<br>` inside content text** — forced breaks don't know the rendered font width, so natural wrap + `<br>` double-breaks. Use `max-width` to let text wrap. Exception: short display titles where each word is deliberately on its own line.
|
||||
- **Animating `visibility` or `display`** — GSAP can't tween these. Use `autoAlpha` (handles both visibility and opacity).
|
||||
- **Calling `video.play()` or `audio.play()`** — the framework owns playback. Never call these yourself.
|
||||
- **Building timelines async** — the capture engine reads `window.__timelines` synchronously after page load. Never wrap timeline construction in `async`, `setTimeout`, or a Promise.
|
||||
- **Standalone `index.html` wrapped in `<template>`** — hides all content from the browser. Only **sub-compositions** loaded via `data-composition-src` use `<template>`.
|
||||
- **Using video for audio** — always muted `<video>` + separate `<audio>`.
|
||||
|
||||
## Verification
|
||||
|
||||
Before and after rendering:
|
||||
|
||||
1. **Lint + validate + inspect pass:** `npx hyperframes lint --strict && npx hyperframes validate && npx hyperframes inspect` (lint catches structural issues, validate catches contrast, inspect catches visual layout / overflow issues — see troubleshooting.md if warnings appear).
|
||||
2. **Animation choreography** — for new compositions or significant animation changes, run the animation map. `npx hyperframes init` copies the skill scripts into the project, so the path is project-local:
|
||||
```bash
|
||||
node skills/hyperframes/scripts/animation-map.mjs <composition-dir> \
|
||||
--out <composition-dir>/.hyperframes/anim-map
|
||||
```
|
||||
Outputs a single `animation-map.json` with per-tween summaries, ASCII Gantt timeline, stagger detection, dead zones (>1s with no animation), element lifecycles, and flags (`offscreen`, `collision`, `invisible`, `paced-fast` <0.2s, `paced-slow` >2s). Scan summaries and flags — fix or justify each. Skip on small edits.
|
||||
3. **File exists + non-zero:** `ls -lh final.mp4`.
|
||||
4. **Duration matches `data-duration`:** `ffprobe -v error -show_entries format=duration -of default=nw=1:nk=1 final.mp4`.
|
||||
5. **Visual check:** extract a mid-composition frame: `ffmpeg -i final.mp4 -ss 00:00:05 -vframes 1 preview.png`.
|
||||
6. **Audio present if expected:** `ffprobe -v error -show_streams -select_streams a -of default=nw=1:nk=1 final.mp4 | head -1`.
|
||||
|
||||
If `hyperframes render` fails, run `npx hyperframes doctor` and attach its output when reporting.
|
||||
|
||||
## References
|
||||
|
||||
- [composition.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/composition.md) — data attributes, timeline contract, non-negotiable rules, typography/asset rules
|
||||
- [cli.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/cli.md) — every CLI command (init, capture, lint, validate, inspect, preview, render, transcribe, tts, doctor, browser, info, upgrade, benchmark)
|
||||
- [gsap.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/gsap.md) — GSAP core API for HyperFrames (tweens, eases, stagger, timelines, matchMedia)
|
||||
- [features.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/features.md) — captions, TTS, audio-reactive, marker highlighting, transitions (load on demand)
|
||||
- [website-to-video.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/website-to-video.md) — 7-step capture-to-video workflow
|
||||
- [troubleshooting.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\hyperframes/references/troubleshooting.md) — OpenClaw fix, env vars, common render errors
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: "Impeccable — Frontend design guidance, upstream-maintained (impeccable)"
|
||||
sidebar_label: "Impeccable"
|
||||
description: "Frontend design guidance, upstream-maintained (impeccable)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Impeccable
|
||||
|
||||
Frontend design guidance, upstream-maintained (impeccable).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/impeccable` |
|
||||
| Path | `optional-skills/creative\impeccable` |
|
||||
| Version | `4.1.2` |
|
||||
| Author | Paul Bakaus (pbakaus) |
|
||||
| License | Apache-2.0 |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `design`, `frontend`, `ui`, `ux`, `web-design`, `anti-slop` |
|
||||
| Related skills | [`claude-design`](/docs/user-guide/skills/bundled/creative/creative-claude-design), [`popular-web-designs`](/docs/user-guide/skills/bundled/creative/creative-popular-web-designs) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Impeccable (upstream-maintained)
|
||||
|
||||
> **Catalog stub.** This entry is maintained upstream at
|
||||
> [pbakaus/impeccable](https://github.com/pbakaus/impeccable): the project
|
||||
> ships and verifies a Hermes-native skill bundle under `.hermes/skills/`.
|
||||
> `hermes skills install impeccable` pulls the current bundle live from that
|
||||
> repo (quarantined and scanned like any hub install) — this directory holds
|
||||
> only the catalog metadata, so the vendored copy can never go stale.
|
||||
|
||||
Impeccable is a design language for AI coding agents: one skill exposing 23
|
||||
sub-commands (`/impeccable init`, `craft`, `shape`, `critique`, `audit`,
|
||||
`polish`, `bolder`, `quieter`, `distill`, `harden`, `onboard`, `animate`,
|
||||
`colorize`, `typeset`, `layout`, `delight`, `overdrive`, `clarify`, `adapt`,
|
||||
`optimize`, `extract`, `document`, `live`), explicit anti-pattern guidance
|
||||
(overused fonts, purple gradients, nested cards, bounce easing), and a
|
||||
61-rule deterministic detector CLI (`npx impeccable detect`) that needs no
|
||||
LLM or API key.
|
||||
|
||||
After install, start with:
|
||||
|
||||
```
|
||||
/impeccable init
|
||||
```
|
||||
|
||||
Full documentation: https://impeccable.style
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
---
|
||||
title: "Kanban Video Orchestrator — Plan and run multi-agent video production pipelines"
|
||||
sidebar_label: "Kanban Video Orchestrator"
|
||||
description: "Plan and run multi-agent video production pipelines"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Kanban Video Orchestrator
|
||||
|
||||
Plan and run multi-agent video production pipelines.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/kanban-video-orchestrator` |
|
||||
| Path | `optional-skills/creative\kanban-video-orchestrator` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | ['SHL0MS', 'alt-glitch'] |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `video`, `kanban`, `multi-agent`, `orchestration`, `production-pipeline` |
|
||||
| Related skills | [`ascii-video`](/docs/user-guide/skills/bundled/creative/creative-ascii-video), [`manim-video`](/docs/user-guide/skills/bundled/creative/creative-manim-video), [`p5js`](/docs/user-guide/skills/bundled/creative/creative-p5js), [`comfyui`](/docs/user-guide/skills/optional/creative/creative-comfyui), [`touchdesigner-mcp`](/docs/user-guide/skills/optional/creative/creative-touchdesigner-mcp), [`pixel-art`](/docs/user-guide/skills/optional/creative/creative-pixel-art), [`ascii-art`](/docs/user-guide/skills/optional/creative/creative-ascii-art), [`songwriting-and-ai-music`](/docs/user-guide/skills/bundled/creative/creative-songwriting-and-ai-music), [`heartmula`](/docs/user-guide/skills/optional/creative/creative-heartmula), [`songsee`](/docs/user-guide/skills/bundled/media/media-songsee), [`youtube-content`](/docs/user-guide/skills/bundled/media/media-youtube-content), [`claude-design`](/docs/user-guide/skills/bundled/creative/creative-claude-design), [`excalidraw`](/docs/user-guide/skills/optional/creative/creative-excalidraw), [`architecture-diagram`](/docs/user-guide/skills/bundled/creative/creative-architecture-diagram), [`concept-diagrams`](/docs/user-guide/skills/optional/creative/creative-concept-diagrams), [`baoyu-comic`](/docs/user-guide/skills/optional/creative/creative-baoyu-comic), [`baoyu-infographic`](/docs/user-guide/skills/bundled/creative/creative-baoyu-infographic), [`humanizer`](/docs/user-guide/skills/bundled/creative/creative-humanizer), [`gif-search`](/docs/user-guide/skills/bundled/media/media-gif-search), [`meme-generation`](/docs/user-guide/skills/optional/creative/creative-meme-generation) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Kanban Video Orchestrator
|
||||
|
||||
Wrap any video request — from a 15-second product teaser to a 5-minute narrative
|
||||
short to a music video to an ASCII loop — in a Hermes Kanban pipeline that
|
||||
decomposes the work to specialized agent profiles.
|
||||
|
||||
This skill does **not** render anything itself. It is a meta-pipeline that:
|
||||
|
||||
1. **Scopes** the request through targeted discovery
|
||||
2. **Designs** an appropriate team (which roles, which tools per role) based on the style
|
||||
3. **Generates** a setup script that creates Hermes profiles, project workspace, and the initial kanban task
|
||||
4. **Hands off** to the director profile, which decomposes via the kanban
|
||||
5. **Monitors** execution, helps intervene when tasks stall or fail
|
||||
|
||||
The actual rendering happens inside the kanban once it's running, via whichever
|
||||
existing skills + tools fit the scenes — `ascii-video`, `manim-video`, `p5js`,
|
||||
`comfyui`, `touchdesigner-mcp`, `songwriting-and-ai-music`,
|
||||
`heartmula`, external APIs, or plain Python with PIL + ffmpeg.
|
||||
|
||||
## When NOT to use this skill
|
||||
|
||||
- The video is one continuous procedural project that needs no specialists. Just write the code directly.
|
||||
- The user wants a quick one-shot conversion (e.g. "convert this mp4 to a GIF") — use ffmpeg directly.
|
||||
- The output is a static image, GIF, or audio-only artifact — use the matching specific skill (`ascii-art`, `gifs`, `meme-generation`, `songwriting-and-ai-music`).
|
||||
- The work fits a single existing skill cleanly (e.g. a pure ASCII video — just use `ascii-video`).
|
||||
|
||||
## Workflow
|
||||
|
||||
```
|
||||
DISCOVER → BRIEF → TEAM DESIGN → SETUP → EXECUTE → MONITOR
|
||||
```
|
||||
|
||||
### Step 1 — Discover (ask the right questions)
|
||||
|
||||
The discovery process is **adaptive**: ask only what is actually needed. Always
|
||||
start with three questions to identify the broad shape:
|
||||
|
||||
- **What is the video?** (one-sentence brief)
|
||||
- **How long?** (5-30s teaser / 30-90s short / 90s-3min explainer / 3-10min film / longer)
|
||||
- **What aspect ratio + target platform?** (1:1 / 9:16 / 16:9; X, IG, YouTube, internal, etc.)
|
||||
|
||||
From the answer, classify the style category. The style determines which
|
||||
follow-up questions to ask. **Do not ask all questions at once.** Ask 2-4 at a
|
||||
time, listen, then proceed. Make reasonable assumptions whenever the user
|
||||
implies an answer.
|
||||
|
||||
For complete intake patterns and per-style question banks, see
|
||||
**[references/intake.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\kanban-video-orchestrator/references/intake.md)**.
|
||||
|
||||
### Step 2 — Brief
|
||||
|
||||
Once enough is known, produce a structured `brief.md` using the template in
|
||||
`assets/brief.md.tmpl`. Stages:
|
||||
|
||||
1. **Concept** — the one-sentence pitch + emotional north star
|
||||
2. **Scope** — duration, aspect, platform, deadline
|
||||
3. **Style** — visual references, brand constraints, tone
|
||||
4. **Scenes** — beat-by-beat breakdown (durations, content, target tool)
|
||||
5. **Audio** — narration / music / SFX / silent (per scene if needed)
|
||||
6. **Deliverables** — file format, resolution, optional alternates (vertical cut, GIF, etc.)
|
||||
|
||||
Show the brief to the user for confirmation before designing the team. **The
|
||||
brief is the contract** — every downstream task references it.
|
||||
|
||||
### Step 3 — Team design
|
||||
|
||||
Pick role archetypes from the library that fit this video. **Compose, don't
|
||||
clone.** Most videos need 4-7 profiles. The director is always present; the
|
||||
rest are picked by what the brief actually requires.
|
||||
|
||||
For the role library and per-style team compositions, see
|
||||
**[references/role-archetypes.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\kanban-video-orchestrator/references/role-archetypes.md)**.
|
||||
|
||||
For mapping role → which Hermes skills + toolsets it loads, see
|
||||
**[references/tool-matrix.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\kanban-video-orchestrator/references/tool-matrix.md)**.
|
||||
|
||||
### Step 4 — Setup
|
||||
|
||||
Generate a setup script (`setup.sh`) and run it. The script:
|
||||
|
||||
1. Creates the project workspace (`~/projects/video-pipeline/<slug>/`)
|
||||
2. Copies any provided assets into `taste/`, `audio/`, `assets/`
|
||||
3. Creates each Hermes profile via `hermes profile create --clone`
|
||||
4. Writes per-profile `SOUL.md` (personality + role definition)
|
||||
5. Configures profile YAML (toolsets, always_load skills, cwd)
|
||||
6. Writes `brief.md`, `TEAM.md`, and `taste/` content
|
||||
7. Fires the initial `hermes kanban create` task assigned to the director
|
||||
|
||||
Use `scripts/bootstrap_pipeline.py` to generate setup.sh from a brief +
|
||||
team-design JSON. See **[references/kanban-setup.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\kanban-video-orchestrator/references/kanban-setup.md)**
|
||||
for the setup script structure, profile config patterns, and the critical
|
||||
"shared workspace" rule.
|
||||
|
||||
### Step 5 — Execute
|
||||
|
||||
Run `setup.sh`. Then provide the user with monitoring commands:
|
||||
|
||||
```bash
|
||||
hermes kanban watch --tenant <project-tenant> # live events
|
||||
hermes kanban list --tenant <project-tenant> # board snapshot
|
||||
hermes dashboard # visual board UI
|
||||
```
|
||||
|
||||
The director profile takes over from here, decomposing the work and routing
|
||||
tasks to specialist profiles via the kanban toolset.
|
||||
|
||||
### Step 6 — Monitor and intervene
|
||||
|
||||
Stay engaged — the kanban runs autonomously but a stuck task or bad output
|
||||
needs human (or AI) judgment.
|
||||
|
||||
Monitoring patterns: poll `kanban list` periodically, inspect any RUNNING task
|
||||
that exceeds its expected duration with `kanban show <id>`, and check
|
||||
heartbeats. When a worker's output fails review, the standard interventions are:
|
||||
|
||||
1. Comment on the worker's task with specific feedback (`kanban_comment`)
|
||||
2. Create a re-run task with the original as parent
|
||||
3. Adjust the brief's scope and let the director re-decompose
|
||||
|
||||
For diagnostic patterns, intervention recipes, and the "task is stuck"
|
||||
playbook, see **[references/monitoring.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\kanban-video-orchestrator/references/monitoring.md)**.
|
||||
|
||||
## Reference: worked examples
|
||||
|
||||
Six concrete pipelines covering very different video styles — narrative film,
|
||||
product/marketing, music video, math/algorithm explainer, ASCII video, real-time
|
||||
installation — showing how the same workflow yields very different teams and
|
||||
task graphs. See **[references/examples.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/creative\kanban-video-orchestrator/references/examples.md)**.
|
||||
|
||||
## Critical rules
|
||||
|
||||
1. **Discovery before action.** Never start generating a brief or team without
|
||||
asking at least the three baseline questions. A bad brief cascades through
|
||||
the entire pipeline.
|
||||
|
||||
2. **Match the team to the video.** Don't reuse the same 4-profile setup for
|
||||
every job. A music video that doesn't have a beat-analysis profile will
|
||||
misfire. A narrative film that doesn't have a writer profile will produce
|
||||
incoherent scenes. See `references/role-archetypes.md`.
|
||||
|
||||
3. **One workspace per project.** All profiles for a given video share the same
|
||||
`dir:` workspace. Tasks pass artifacts via shared filesystem and structured
|
||||
handoffs. **Every** `kanban_create` call passes
|
||||
`workspace_kind="dir"` + `workspace_path="<absolute project path>"`.
|
||||
|
||||
4. **Tenant every project.** Use a project-specific tenant
|
||||
(`--tenant <project-slug>`). Keeps the dashboard scoped and prevents
|
||||
cross-pollination with other ongoing kanbans.
|
||||
|
||||
5. **Respect existing skills.** When a scene fits an existing skill, the
|
||||
relevant renderer should load that skill via `--skill <name>` on its task
|
||||
or `always_load` in its profile. Do not re-derive what a skill already
|
||||
provides.
|
||||
|
||||
6. **The director never executes.** Even with the full `kanban + terminal +
|
||||
file` toolset, the director's `SOUL.md` rules forbid it from executing
|
||||
work itself. It decomposes and routes only — every concrete task becomes
|
||||
a `hermes kanban create` call to a specialist profile. The kanban
|
||||
orchestration guidance auto-injected into every kanban worker's system
|
||||
prompt spells this out further.
|
||||
|
||||
7. **Don't over-decompose.** A 30-second product video does NOT need 20 tasks.
|
||||
Aim for the smallest task graph that still parallelizes well and exposes the
|
||||
right human-review gates.
|
||||
|
||||
8. **Verify API keys BEFORE firing.** External APIs (TTS, image-gen,
|
||||
image-to-video) need keys in `${HERMES_HOME:-~/.hermes}/.env` or the user's secret store.
|
||||
A worker that hits a missing-key error wastes a task slot. The setup
|
||||
script's `check_key` helper aborts cleanly if a required key is missing.
|
||||
|
||||
## File map
|
||||
|
||||
```
|
||||
SKILL.md ← this file (workflow + rules)
|
||||
references/
|
||||
intake.md ← discovery question banks per style
|
||||
role-archetypes.md ← role library (writer, designer, animator, …)
|
||||
tool-matrix.md ← skill + toolset mapping per role
|
||||
kanban-setup.md ← setup script structure & profile config
|
||||
monitoring.md ← watch + intervene patterns
|
||||
examples.md ← six worked pipelines
|
||||
assets/
|
||||
brief.md.tmpl ← brief skeleton
|
||||
setup.sh.tmpl ← setup script skeleton
|
||||
soul.md.tmpl ← profile personality skeleton
|
||||
scripts/
|
||||
bootstrap_pipeline.py ← generate setup.sh from brief + team JSON
|
||||
monitor.py ← polling + intervention helpers
|
||||
```
|
||||
@@ -0,0 +1,147 @@
|
||||
---
|
||||
title: "Meme Generation — Create meme PNGs from templates with Pillow text overlay"
|
||||
sidebar_label: "Meme Generation"
|
||||
description: "Create meme PNGs from templates with Pillow text overlay"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Meme Generation
|
||||
|
||||
Create meme PNGs from templates with Pillow text overlay.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/meme-generation` |
|
||||
| Path | `optional-skills/creative\meme-generation` |
|
||||
| Version | `2.0.0` |
|
||||
| Author | adanaleycio |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `creative`, `memes`, `humor`, `images` |
|
||||
| Related skills | [`ascii-art`](/docs/user-guide/skills/optional/creative/creative-ascii-art) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Meme Generation
|
||||
|
||||
Generate actual meme images from a topic. Picks a template, writes captions, and renders a real .png file with text overlay.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks you to make or generate a meme
|
||||
- User wants a meme about a specific topic, situation, or frustration
|
||||
- User says "meme this" or similar
|
||||
|
||||
## Available Templates
|
||||
|
||||
The script supports **any of the ~100 popular imgflip templates** by name or ID, plus 10 curated templates with hand-tuned text positioning.
|
||||
|
||||
### Curated Templates (custom text placement)
|
||||
|
||||
| ID | Name | Fields | Best for |
|
||||
|----|------|--------|----------|
|
||||
| `this-is-fine` | This is Fine | top, bottom | chaos, denial |
|
||||
| `drake` | Drake Hotline Bling | reject, approve | rejecting/preferring |
|
||||
| `distracted-boyfriend` | Distracted Boyfriend | distraction, current, person | temptation, shifting priorities |
|
||||
| `two-buttons` | Two Buttons | left, right, person | impossible choice |
|
||||
| `expanding-brain` | Expanding Brain | 4 levels | escalating irony |
|
||||
| `change-my-mind` | Change My Mind | statement | hot takes |
|
||||
| `woman-yelling-at-cat` | Woman Yelling at Cat | woman, cat | arguments |
|
||||
| `one-does-not-simply` | One Does Not Simply | top, bottom | deceptively hard things |
|
||||
| `grus-plan` | Gru's Plan | step1-3, realization | plans that backfire |
|
||||
| `batman-slapping-robin` | Batman Slapping Robin | robin, batman | shutting down bad ideas |
|
||||
|
||||
### Dynamic Templates (from imgflip API)
|
||||
|
||||
Any template not in the curated list can be used by name or imgflip ID. These get smart default text positioning (top/bottom for 2-field, evenly spaced for 3+). Search with:
|
||||
```bash
|
||||
python "$SKILL_DIR/scripts/generate_meme.py" --search "disaster"
|
||||
```
|
||||
|
||||
## Procedure
|
||||
|
||||
### Mode 1: Classic Template (default)
|
||||
|
||||
1. Read the user's topic and identify the core dynamic (chaos, dilemma, preference, irony, etc.)
|
||||
2. Pick the template that best matches. Use the "Best for" column, or search with `--search`.
|
||||
3. Write short captions for each field (8-12 words max per field, shorter is better).
|
||||
4. Find the skill's script directory:
|
||||
```
|
||||
SKILL_DIR=$(dirname "$(find ~/.hermes/skills -path '*/meme-generation/SKILL.md' 2>/dev/null | head -1)")
|
||||
```
|
||||
5. Run the generator:
|
||||
```bash
|
||||
python "$SKILL_DIR/scripts/generate_meme.py" <template_id> /tmp/meme.png "caption 1" "caption 2" ...
|
||||
```
|
||||
6. Return the image with `MEDIA:/tmp/meme.png`
|
||||
|
||||
### Mode 2: Custom AI Image (when image_generate is available)
|
||||
|
||||
Use this when no classic template fits, or when the user wants something original.
|
||||
|
||||
1. Write the captions first.
|
||||
2. Use `image_generate` to create a scene that matches the meme concept. Do NOT include any text in the image prompt — text will be added by the script. Describe only the visual scene.
|
||||
3. Find the generated image path from the image_generate result URL. Download it to a local path if needed.
|
||||
4. Run the script with `--image` to overlay text, choosing a mode:
|
||||
- **Overlay** (text directly on image, white with black outline):
|
||||
```bash
|
||||
python "$SKILL_DIR/scripts/generate_meme.py" --image /path/to/scene.png /tmp/meme.png "top text" "bottom text"
|
||||
```
|
||||
- **Bars** (black bars above/below with white text — cleaner, always readable):
|
||||
```bash
|
||||
python "$SKILL_DIR/scripts/generate_meme.py" --image /path/to/scene.png --bars /tmp/meme.png "top text" "bottom text"
|
||||
```
|
||||
Use `--bars` when the image is busy/detailed and text would be hard to read on top of it.
|
||||
5. **Verify with vision** (if `vision_analyze` is available): Check the result looks good:
|
||||
```
|
||||
vision_analyze(image_url="/tmp/meme.png", question="Is the text legible and well-positioned? Does the meme work visually?")
|
||||
```
|
||||
If the vision model flags issues (text hard to read, bad placement, etc.), try the other mode (switch between overlay and bars) or regenerate the scene.
|
||||
6. Return the image with `MEDIA:/tmp/meme.png`
|
||||
|
||||
## Examples
|
||||
|
||||
**"debugging production at 2 AM":**
|
||||
```bash
|
||||
python generate_meme.py this-is-fine /tmp/meme.png "SERVERS ARE ON FIRE" "This is fine"
|
||||
```
|
||||
|
||||
**"choosing between sleep and one more episode":**
|
||||
```bash
|
||||
python generate_meme.py drake /tmp/meme.png "Getting 8 hours of sleep" "One more episode at 3 AM"
|
||||
```
|
||||
|
||||
**"the stages of a Monday morning":**
|
||||
```bash
|
||||
python generate_meme.py expanding-brain /tmp/meme.png "Setting an alarm" "Setting 5 alarms" "Sleeping through all alarms" "Working from bed"
|
||||
```
|
||||
|
||||
## Listing Templates
|
||||
|
||||
To see all available templates:
|
||||
```bash
|
||||
python generate_meme.py --list
|
||||
```
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Keep captions SHORT. Memes with long text look terrible.
|
||||
- Match the number of text arguments to the template's field count.
|
||||
- Pick the template that fits the joke structure, not just the topic.
|
||||
- Do not generate hateful, abusive, or personally targeted content.
|
||||
- The script caches template images in `scripts/.cache/` after first download.
|
||||
|
||||
## Verification
|
||||
|
||||
The output is correct if:
|
||||
- A .png file was created at the output path
|
||||
- Text is legible (white with black outline) on the template
|
||||
- The joke lands — caption matches the template's intended structure
|
||||
- File can be delivered via MEDIA: path
|
||||
@@ -0,0 +1,234 @@
|
||||
---
|
||||
title: "Pixel Art — Pixel art w/ era palettes (NES, Game Boy, PICO-8)"
|
||||
sidebar_label: "Pixel Art"
|
||||
description: "Pixel art w/ era palettes (NES, Game Boy, PICO-8)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Pixel Art
|
||||
|
||||
Pixel art w/ era palettes (NES, Game Boy, PICO-8).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/pixel-art` |
|
||||
| Path | `optional-skills/creative\pixel-art` |
|
||||
| Version | `2.0.0` |
|
||||
| Author | dodo-reach |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `creative`, `pixel-art`, `arcade`, `snes`, `nes`, `gameboy`, `retro`, `image`, `video` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Pixel Art
|
||||
|
||||
Convert any image into retro pixel art, then optionally animate it into a short
|
||||
MP4 or GIF with era-appropriate effects (rain, fireflies, snow, embers).
|
||||
|
||||
Two scripts ship with this skill:
|
||||
|
||||
- `scripts/pixel_art.py` — photo → pixel-art PNG (Floyd-Steinberg dithering)
|
||||
- `scripts/pixel_art_video.py` — pixel-art PNG → animated MP4 (+ optional GIF)
|
||||
|
||||
Each is importable or runnable directly. Presets snap to hardware palettes
|
||||
when you want era-accurate colors (NES, Game Boy, PICO-8, etc.), or use
|
||||
adaptive N-color quantization for arcade/SNES-style looks.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User wants retro pixel art from a source image
|
||||
- User asks for NES / Game Boy / PICO-8 / C64 / arcade / SNES styling
|
||||
- User wants a short looping animation (rain scene, night sky, snow, etc.)
|
||||
- Posters, album covers, social posts, sprites, characters, avatars
|
||||
|
||||
## Workflow
|
||||
|
||||
Before generating, confirm the style with the user. Different presets produce
|
||||
very different outputs and regenerating is costly.
|
||||
|
||||
### Step 1 — Offer a style
|
||||
|
||||
Call `clarify` with 4 representative presets. Pick the set based on what the
|
||||
user asked for — don't just dump all 14.
|
||||
|
||||
Default menu when the user's intent is unclear:
|
||||
|
||||
```python
|
||||
clarify(
|
||||
question="Which pixel-art style do you want?",
|
||||
choices=[
|
||||
"arcade — bold, chunky 80s cabinet feel (16 colors, 8px)",
|
||||
"nes — Nintendo 8-bit hardware palette (54 colors, 8px)",
|
||||
"gameboy — 4-shade green Game Boy DMG",
|
||||
"snes — cleaner 16-bit look (32 colors, 4px)",
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
When the user already named an era (e.g. "80s arcade", "Gameboy"), skip
|
||||
`clarify` and use the matching preset directly.
|
||||
|
||||
### Step 2 — Offer animation (optional)
|
||||
|
||||
If the user asked for a video/GIF, or the output might benefit from motion,
|
||||
ask which scene:
|
||||
|
||||
```python
|
||||
clarify(
|
||||
question="Want to animate it? Pick a scene or skip.",
|
||||
choices=[
|
||||
"night — stars + fireflies + leaves",
|
||||
"urban — rain + neon pulse",
|
||||
"snow — falling snowflakes",
|
||||
"skip — just the image",
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
Do NOT call `clarify` more than twice in a row. One for style, one for scene if
|
||||
animation is on the table. If the user explicitly asked for a specific style
|
||||
and scene in their message, skip `clarify` entirely.
|
||||
|
||||
### Step 3 — Generate
|
||||
|
||||
Run `pixel_art()` first; if animation was requested, chain into
|
||||
`pixel_art_video()` on the result.
|
||||
|
||||
## Preset Catalog
|
||||
|
||||
| Preset | Era | Palette | Block | Best for |
|
||||
|--------|-----|---------|-------|----------|
|
||||
| `arcade` | 80s arcade | adaptive 16 | 8px | Bold posters, hero art |
|
||||
| `snes` | 16-bit | adaptive 32 | 4px | Characters, detailed scenes |
|
||||
| `nes` | 8-bit | NES (54) | 8px | True NES look |
|
||||
| `gameboy` | DMG handheld | 4 green shades | 8px | Monochrome Game Boy |
|
||||
| `gameboy_pocket` | Pocket handheld | 4 grey shades | 8px | Mono GB Pocket |
|
||||
| `pico8` | PICO-8 | 16 fixed | 6px | Fantasy-console look |
|
||||
| `c64` | Commodore 64 | 16 fixed | 8px | 8-bit home computer |
|
||||
| `apple2` | Apple II hi-res | 6 fixed | 10px | Extreme retro, 6 colors |
|
||||
| `teletext` | BBC Teletext | 8 pure | 10px | Chunky primary colors |
|
||||
| `mspaint` | Windows MS Paint | 24 fixed | 8px | Nostalgic desktop |
|
||||
| `mono_green` | CRT phosphor | 2 green | 6px | Terminal/CRT aesthetic |
|
||||
| `mono_amber` | CRT amber | 2 amber | 6px | Amber monitor look |
|
||||
| `neon` | Cyberpunk | 10 neons | 6px | Vaporwave/cyber |
|
||||
| `pastel` | Soft pastel | 10 pastels | 6px | Kawaii / gentle |
|
||||
|
||||
Named palettes live in `scripts/palettes.py` (see `references/palettes.md` for
|
||||
the complete list — 28 named palettes total). Any preset can be overridden:
|
||||
|
||||
```python
|
||||
pixel_art("in.png", "out.png", preset="snes", palette="PICO_8", block=6)
|
||||
```
|
||||
|
||||
## Scene Catalog (for video)
|
||||
|
||||
| Scene | Effects |
|
||||
|-------|---------|
|
||||
| `night` | Twinkling stars + fireflies + drifting leaves |
|
||||
| `dusk` | Fireflies + sparkles |
|
||||
| `tavern` | Dust motes + warm sparkles |
|
||||
| `indoor` | Dust motes |
|
||||
| `urban` | Rain + neon pulse |
|
||||
| `nature` | Leaves + fireflies |
|
||||
| `magic` | Sparkles + fireflies |
|
||||
| `storm` | Rain + lightning |
|
||||
| `underwater` | Bubbles + light sparkles |
|
||||
| `fire` | Embers + sparkles |
|
||||
| `snow` | Snowflakes + sparkles |
|
||||
| `desert` | Heat shimmer + dust |
|
||||
|
||||
## Invocation Patterns
|
||||
|
||||
### Python (import)
|
||||
|
||||
```python
|
||||
import sys
|
||||
import os
|
||||
sys.path.insert(0, os.path.expanduser("~/.hermes/skills/creative/pixel-art/scripts"))
|
||||
from pixel_art import pixel_art
|
||||
from pixel_art_video import pixel_art_video
|
||||
|
||||
# 1. Convert to pixel art
|
||||
pixel_art("/path/to/photo.jpg", "/tmp/pixel.png", preset="nes")
|
||||
|
||||
# 2. Animate (optional)
|
||||
pixel_art_video(
|
||||
"/tmp/pixel.png",
|
||||
"/tmp/pixel.mp4",
|
||||
scene="night",
|
||||
duration=6,
|
||||
fps=15,
|
||||
seed=42,
|
||||
export_gif=True,
|
||||
)
|
||||
```
|
||||
|
||||
### CLI
|
||||
|
||||
```bash
|
||||
cd ~/.hermes/skills/creative/pixel-art/scripts
|
||||
|
||||
python pixel_art.py in.jpg out.png --preset gameboy
|
||||
python pixel_art.py in.jpg out.png --preset snes --palette PICO_8 --block 6
|
||||
|
||||
python pixel_art_video.py out.png out.mp4 --scene night --duration 6 --gif
|
||||
```
|
||||
|
||||
## Pipeline Rationale
|
||||
|
||||
**Pixel conversion:**
|
||||
1. Boost contrast/color/sharpness (stronger for smaller palettes)
|
||||
2. Posterize to simplify tonal regions before quantization
|
||||
3. Downscale by `block` with `Image.NEAREST` (hard pixels, no interpolation)
|
||||
4. Quantize with Floyd-Steinberg dithering — against either an adaptive
|
||||
N-color palette OR a named hardware palette
|
||||
5. Upscale back with `Image.NEAREST`
|
||||
|
||||
Quantizing AFTER downscale keeps dithering aligned with the final pixel grid.
|
||||
Quantizing before would waste error-diffusion on detail that disappears.
|
||||
|
||||
**Video overlay:**
|
||||
- Copies the base frame each tick (static background)
|
||||
- Overlays stateless-per-frame particle draws (one function per effect)
|
||||
- Encodes via ffmpeg `libx264 -pix_fmt yuv420p -crf 18`
|
||||
- Optional GIF via `palettegen` + `paletteuse`
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Python 3.9+
|
||||
- Pillow (`pip install Pillow`)
|
||||
- ffmpeg on PATH (only needed for video — Hermes installs package this)
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Pallet keys are case-sensitive (`"NES"`, `"PICO_8"`, `"GAMEBOY_ORIGINAL"`).
|
||||
- Very small sources (<100px wide) collapse under 8-10px blocks. Upscale the
|
||||
source first if it's tiny.
|
||||
- Fractional `block` or `palette` will break quantization — keep them positive ints.
|
||||
- Animation particle counts are tuned for ~640x480 canvases. On very large
|
||||
images you may want a second pass with a different seed for density.
|
||||
- `mono_green` / `mono_amber` force `color=0.0` (desaturate). If you override
|
||||
and keep chroma, the 2-color palette can produce stripes on smooth regions.
|
||||
- `clarify` loop: call it at most twice per turn (style, then scene). Don't
|
||||
pepper the user with more picks.
|
||||
|
||||
## Verification
|
||||
|
||||
- PNG is created at the output path
|
||||
- Clear square pixel blocks visible at the preset's block size
|
||||
- Color count matches preset (eyeball the image or run `Image.open(p).getcolors()`)
|
||||
- Video is a valid MP4 (`ffprobe` can open it) with non-zero size
|
||||
|
||||
## Attribution
|
||||
|
||||
Named hardware palettes and the procedural animation loops in `pixel_art_video.py`
|
||||
are ported from [pixel-art-studio](https://github.com/Synero/pixel-art-studio)
|
||||
(MIT). See `ATTRIBUTION.md` in this skill directory for details.
|
||||
@@ -0,0 +1,238 @@
|
||||
---
|
||||
title: "Pretext — Build creative browser demos with DOM-free text layout"
|
||||
sidebar_label: "Pretext"
|
||||
description: "Build creative browser demos with DOM-free text layout"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Pretext
|
||||
|
||||
Build creative browser demos with DOM-free text layout.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/pretext` |
|
||||
| Path | `optional-skills/creative\pretext` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `creative-coding`, `typography`, `pretext`, `ascii-art`, `canvas`, `generative`, `text-layout`, `kinetic-typography` |
|
||||
| Related skills | [`p5js`](/docs/user-guide/skills/bundled/creative/creative-p5js), [`claude-design`](/docs/user-guide/skills/bundled/creative/creative-claude-design), [`excalidraw`](/docs/user-guide/skills/optional/creative/creative-excalidraw), [`architecture-diagram`](/docs/user-guide/skills/bundled/creative/creative-architecture-diagram) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Pretext Creative Demos
|
||||
|
||||
## Overview
|
||||
|
||||
[`@chenglou/pretext`](https://github.com/chenglou/pretext) is a 15KB zero-dependency TypeScript library by Cheng Lou (React core, ReasonML, Midjourney) for **DOM-free multiline text measurement and layout**. It does one thing: given `(text, font, width)`, return the line breaks, per-line widths, per-grapheme positions, and total height — all via canvas measurement, no reflow.
|
||||
|
||||
That sounds like plumbing. It is not. Because it is fast and geometric, it is a **creative primitive**: you can reflow paragraphs around a moving sprite at 60fps, build games whose level geometry is made of real words, drive ASCII logos through prose, shatter text into particles with exact per-grapheme starting positions, or pack shrink-wrapped multiline UI without any `getBoundingClientRect` thrash.
|
||||
|
||||
This skill exists so Hermes can make **cool demos** with it — the kind people post to X. See `pretext.cool` and `chenglou.me/pretext` for the community demo corpus.
|
||||
|
||||
## When to Use
|
||||
|
||||
Use when the user asks for:
|
||||
- A "pretext demo" / "cool pretext thing" / "text-as-X"
|
||||
- Text flowing around a moving shape (hero sections, editorial layouts, animated long-form pages)
|
||||
- ASCII-art effects using **real words or prose**, not monospace rasters
|
||||
- Games where the playfield / obstacles / bricks are made of text (Tetris-from-letters, Breakout-of-prose)
|
||||
- Kinetic typography with per-glyph physics (shatter, scatter, flock, flow)
|
||||
- Typographic generative art, especially with non-Latin scripts or mixed scripts
|
||||
- Multiline "shrink-wrap" UI (smallest container width that still fits the text)
|
||||
- Anything that would require knowing line breaks *before* rendering
|
||||
|
||||
Don't use for:
|
||||
- Static SVG/HTML pages where CSS already solves layout — just use CSS
|
||||
- Rich text editors, general inline formatting engines (pretext is intentionally narrow)
|
||||
- Image → text (use `ascii-art` / `ascii-video` skills)
|
||||
- Pure canvas generative art with no text role — use `p5js`
|
||||
|
||||
## Creative Standard
|
||||
|
||||
This is visual art rendered in a browser. Pretext returns numbers; **you** draw the thing.
|
||||
|
||||
- **Don't ship a "hello world" demo.** The `hello-orb-flow.html` template is the *starting* point. Every delivered demo must add intentional color, motion, composition, and one visual detail the user didn't ask for but will appreciate.
|
||||
- **Dark backgrounds, warm cores, considered palette.** Classic amber-on-black (CRT / terminal) works, but so do cold-white-on-charcoal (editorial) and desaturated pastels (risograph). Pick one and commit.
|
||||
- **Proportional fonts are the point.** Pretext's whole vibe is "not monospaced" — lean into it. Use Iowan Old Style, Inter, JetBrains Mono, Helvetica Neue, or a variable font. Never default sans.
|
||||
- **Real source/text, not lorem ipsum.** The corpus should mean something. Short manifestos, poetry, real source code, a found text, the library's own README — never `lorem ipsum`.
|
||||
- **First-paint excellence.** No loading states, no blank frames. The demo must look shippable the instant it opens.
|
||||
|
||||
## Stack
|
||||
|
||||
Single self-contained HTML file per demo. No build step.
|
||||
|
||||
| Layer | Tool | Purpose |
|
||||
|-------|------|---------|
|
||||
| Core | `@chenglou/pretext` via `esm.sh` CDN | Text measurement + line layout |
|
||||
| Render | HTML5 Canvas 2D | Glyph rendering, per-frame composition |
|
||||
| Segmentation | `Intl.Segmenter` (built-in) | Grapheme splitting for emoji / CJK / combining marks |
|
||||
| Interaction | Raw DOM events | Mouse / touch / wheel — no framework |
|
||||
|
||||
```html
|
||||
<script type="module">
|
||||
import {
|
||||
prepare, layout, // use-case 1: simple height
|
||||
prepareWithSegments, layoutWithLines, // use-case 2a: fixed-width lines
|
||||
layoutNextLineRange, materializeLineRange, // use-case 2b: streaming / variable width
|
||||
measureLineStats, walkLineRanges, // stats without string allocation
|
||||
} from "https://esm.sh/@chenglou/pretext@0.0.6";
|
||||
</script>
|
||||
```
|
||||
|
||||
Pin the version. `@0.0.6` at time of writing — check [npm](https://www.npmjs.com/package/@chenglou/pretext) for the latest if demo behavior is off.
|
||||
|
||||
## The Two Use Cases
|
||||
|
||||
Almost everything reduces to one of these two shapes. Learn both.
|
||||
|
||||
### Use-case 1 — measure, then render with CSS/DOM
|
||||
|
||||
```js
|
||||
const prepared = prepare(text, "16px Inter");
|
||||
const { height, lineCount } = layout(prepared, 320, 20);
|
||||
```
|
||||
|
||||
You still let the browser draw the text. Pretext just tells you how tall the box will be at a given width, **without** a DOM read. Use for:
|
||||
- Virtualized lists where rows contain wrapping text
|
||||
- Masonry with precise card heights
|
||||
- "Does this label fit?" dev-time checks
|
||||
- Preventing layout shift when remote text loads
|
||||
|
||||
**Keep `font` and `letterSpacing` exactly in sync with your CSS.** The canvas `ctx.font` format (e.g. `"16px Inter"`, `"500 17px 'JetBrains Mono'"`) must match the rendered CSS, or measurements drift.
|
||||
|
||||
### Use-case 2 — measure *and* render yourself
|
||||
|
||||
```js
|
||||
const prepared = prepareWithSegments(text, FONT);
|
||||
const { lines } = layoutWithLines(prepared, 320, 26);
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
ctx.fillText(lines[i].text, 0, i * 26);
|
||||
}
|
||||
```
|
||||
|
||||
This is where the creative work lives. You own the drawing, so you can:
|
||||
- Render to canvas, SVG, WebGL, or any coordinate system
|
||||
- Substitute per-glyph transforms (rotation, jitter, scale, opacity)
|
||||
- Use line metadata (width, grapheme positions) as geometry
|
||||
|
||||
For **variable-width-per-line** flow (text around a shape, text in a donut band, text in a non-rectangular column):
|
||||
|
||||
```js
|
||||
let cursor = { segmentIndex: 0, graphemeIndex: 0 };
|
||||
let y = 0;
|
||||
while (true) {
|
||||
const lineWidth = widthAtY(y); // your function: how wide is the corridor at this y?
|
||||
const range = layoutNextLineRange(prepared, cursor, lineWidth);
|
||||
if (!range) break;
|
||||
const line = materializeLineRange(prepared, range);
|
||||
ctx.fillText(line.text, leftEdgeAtY(y), y);
|
||||
cursor = range.end;
|
||||
y += lineHeight;
|
||||
}
|
||||
```
|
||||
|
||||
This is the most important pattern in the whole library. It's what unlocks "text flowing around a dragged sprite" — the demo that went viral on X.
|
||||
|
||||
### Helpers worth knowing
|
||||
|
||||
- `measureLineStats(prepared, maxWidth)` → `{ lineCount, maxLineWidth }` — the widest line, i.e. multiline shrink-wrap width.
|
||||
- `walkLineRanges(prepared, maxWidth, callback)` — iterate lines without allocating strings. Use for stats/physics over graphemes when you don't need the characters.
|
||||
- `@chenglou/pretext/rich-inline` — the same system but for paragraphs mixing fonts / chips / mentions. Import from the subpath.
|
||||
|
||||
## Demo Recipe Patterns
|
||||
|
||||
The community corpus (see `references/patterns.md`) clusters into a handful of strong patterns. Pick one and riff — don't invent a new category unless asked.
|
||||
|
||||
| Pattern | Key API | Example idea |
|
||||
|---|---|---|
|
||||
| **Reflow around obstacle** | `layoutNextLineRange` + per-row width function | Editorial paragraph that parts around a dragged cursor sprite |
|
||||
| **Text-as-geometry game** | `layoutWithLines` + per-line collision rects | Breakout where each brick is a measured word |
|
||||
| **Shatter / particles** | `walkLineRanges` → per-grapheme (x,y) → physics | Sentence that explodes into letters on click |
|
||||
| **ASCII obstacle typography** | `layoutNextLineRange` + measured per-row obstacle spans | Bitmap ASCII logo, shape morphs, and draggable wire objects that make text open around their actual geometry |
|
||||
| **Editorial multi-column** | `layoutNextLineRange` per column + shared cursor | Animated magazine spread with pull quotes |
|
||||
| **Kinetic type** | `layoutWithLines` + per-line transform over time | Star Wars crawl, wave, bounce, glitch |
|
||||
| **Multiline shrink-wrap** | `measureLineStats` | Quote card that auto-sizes to its tightest container |
|
||||
|
||||
See `templates/donut-orbit.html` and `templates/hello-orb-flow.html` for working single-file starters.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Pick a pattern** from the table above based on the user's brief.
|
||||
2. **Start from a template**:
|
||||
- `templates/hello-orb-flow.html` — text reflowing around a moving orb (reflow-around-obstacle pattern)
|
||||
- `templates/donut-orbit.html` — advanced example: measured ASCII logo obstacles, draggable wire sphere/cube, morphing shape fields, selectable DOM text, and dev-only controls
|
||||
- `write_file` to a new `.html` in `/tmp/` or the user's workspace.
|
||||
3. **Swap the corpus** for something intentional to the brief. Real prose, 10-100 sentences, no lorem.
|
||||
4. **Tune the aesthetic** — font, palette, composition, interaction. This is the work; don't skip it.
|
||||
5. **Verify locally**:
|
||||
```sh
|
||||
cd <dir-with-html> && python -m http.server 8765
|
||||
# then open http://localhost:8765/<file>.html
|
||||
```
|
||||
6. **Check the console** — pretext will throw if `prepareWithSegments` is called with a bad font string; `Intl.Segmenter` is available in every modern browser.
|
||||
7. **Show the user the file path**, not just the code — they want to open it.
|
||||
|
||||
## Performance Notes
|
||||
|
||||
- `prepare()` / `prepareWithSegments()` is the expensive call. Do it **once** per text+font pair. Cache the handle.
|
||||
- On resize, only rerun `layout()` / `layoutWithLines()` — never re-prepare.
|
||||
- For per-frame animations where text doesn't change but geometry does, `layoutNextLineRange` in a tight loop is cheap enough to do every frame at 60fps for normal-length paragraphs.
|
||||
- When rendering ASCII masks per frame, keep a cell buffer (`Uint8Array`/typed arrays), derive measured per-row obstacle spans from the cells or projected geometry, merge spans, then feed those spans into `layoutNextLineRange` before drawing text.
|
||||
- Keep visual animation and layout animation coupled. If a sphere morphs into a cube, tween both the rendered cell buffer and the obstacle spans with the same value; otherwise the demo looks painted-on instead of physically reflowed.
|
||||
- For fades, prefer layer opacity over changing glyph intensity or obstacle scale. Put transient ASCII sprites on their own canvas and fade the canvas with CSS/GSAP opacity so geometry does not appear to shrink.
|
||||
- Canvas `ctx.font` setting is surprisingly slow; set it **once** per frame if font doesn't vary, not per `fillText` call.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
1. **Drifting CSS/canvas font strings.** `ctx.font = "16px Inter"` measured, but CSS says `font-family: Inter, sans-serif; font-size: 16px`. Fine *if* Inter loads. If Inter 404s, CSS falls back to sans-serif and measurements drift by 5-20%. Always `preload` the font or use a web-safe family.
|
||||
|
||||
2. **Re-preparing inside the animation loop.** Only `layout*` is cheap. Re-calling `prepare` every frame will tank perf. Keep the prepared handle in module scope.
|
||||
|
||||
3. **Forgetting `Intl.Segmenter` for grapheme splits.** Emoji, combining marks, CJK — `"é".split("")` gives you two chars. Use `new Intl.Segmenter(undefined, { granularity: "grapheme" })` when sampling individual visible glyphs.
|
||||
|
||||
4. **`break: 'never'` chips without `extraWidth`.** In `rich-inline`, if you use `break: 'never'` for an atomic chip/mention, you must also supply `extraWidth` for the pill padding — otherwise chip chrome overflows the container.
|
||||
|
||||
5. **Using `@chenglou/pretext` from `unpkg` with TypeScript-only entry.** Use `esm.sh` — it compiles the TS exports to browser-ready ESM automatically. `unpkg` will 404 or serve raw TS.
|
||||
|
||||
6. **Monospace fallbacks silently erasing the whole point.** Users seeing monospace-looking output often have a CSS `font-family` that fell through to `monospace`. Verify the actual rendered font via DevTools.
|
||||
|
||||
7. **Skipping rows vs adjusting width** when flowing around a shape. If the corridor on this row is too narrow to fit a line, *skip the row* (`y += lineHeight; continue;`) rather than passing a tiny maxWidth to `layoutNextLineRange` — pretext will return one-grapheme lines that look broken.
|
||||
|
||||
8. **Shipping a cold demo.** The default first-paint looks tutorial-grade. Add: vignette, subtle scanline, idle auto-motion, one carefully chosen interactive response (drag, hover, scroll, click). Without these, "cool pretext demo" lands as "intern repro of the README."
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
- [ ] Demo is a single self-contained `.html` file — opens by double-click or `python -m http.server`
|
||||
- [ ] `@chenglou/pretext` imported via `esm.sh` with pinned version
|
||||
- [ ] Corpus is real prose, not lorem ipsum, and matches the demo's concept
|
||||
- [ ] Font string passed to `prepare` matches the CSS font exactly
|
||||
- [ ] `prepare()` / `prepareWithSegments()` called once, not per frame
|
||||
- [ ] Dark background + considered palette — not the default white canvas
|
||||
- [ ] At least one interactive response (drag / hover / scroll / click) or idle auto-motion
|
||||
- [ ] Tested locally with `python -m http.server` and confirmed no console errors
|
||||
- [ ] 60fps on a mid-tier laptop (or graceful degradation documented)
|
||||
- [ ] One "extra mile" detail the user didn't ask for
|
||||
|
||||
## Reference: Community Demos
|
||||
|
||||
Clone these for inspiration / patterns (all MIT-ish, linked from [pretext.cool](https://www.pretext.cool/)):
|
||||
|
||||
- **Pretext Breaker** — breakout with word-bricks — `github.com/rinesh/pretext-breaker`
|
||||
- **Tetris × Pretext** — `github.com/shinichimochizuki/tetris-pretext`
|
||||
- **Dragon animation** — `github.com/qtakmalay/PreTextExperiments`
|
||||
- **Somnai editorial engine** — `github.com/somnai-dreams/pretext-demos`
|
||||
- **Bad Apple!! ASCII** — `github.com/frmlinn/bad-apple-pretext`
|
||||
- **Drag-sprite reflow** — `github.com/dokobot/pretext-demo`
|
||||
- **Alarmy editorial clock** — `github.com/SmisLee/alarmy-pretext-demo`
|
||||
|
||||
Official playground: [chenglou.me/pretext](https://chenglou.me/pretext/) — accordion, bubbles, dynamic-layout, editorial-engine, justification-comparison, masonry, markdown-chat, rich-note.
|
||||
@@ -0,0 +1,362 @@
|
||||
---
|
||||
title: "Simple English — Rewrite text to ASD-STE100 Simplified Technical English"
|
||||
sidebar_label: "Simple English"
|
||||
description: "Rewrite text to ASD-STE100 Simplified Technical English"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Simple English
|
||||
|
||||
Rewrite text to ASD-STE100 Simplified Technical English.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/simple-english` |
|
||||
| Path | `optional-skills/creative\simple-english` |
|
||||
| Version | `1.2.0` |
|
||||
| Author | AminBlg (https://github.com/AminBlg/SimpleEnglish), ported by Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `writing`, `documentation`, `ste`, `asd-ste100`, `technical-writing`, `editing`, `anti-ai-slop` |
|
||||
| Related skills | [`humanizer`](/docs/user-guide/skills/bundled/creative/creative-humanizer) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Simple English: Write Like an Aerospace Manual
|
||||
|
||||
Write technical text with the rules of ASD-STE100 Simplified Technical English. STE is the controlled language that aerospace and defense manufacturers use for maintenance documentation. The rules exist so that a tired reader who is not a native English speaker cannot misread an instruction. They remove the usual signs of AI-generated text as a side effect: long sentences, synonym rotation, hedges, filler, and decorative clauses.
|
||||
|
||||
Write for that tired reader. Each sentence must survive one read.
|
||||
|
||||
## How to use it in Hermes
|
||||
|
||||
The text usually arrives one of three ways:
|
||||
|
||||
1. **Inline.** The user pastes the text into the message. Rewrite it in place and reply with the result.
|
||||
2. **File.** The user points at a file (README, runbook, docs page). Use `read_file` to load it, then `patch` for targeted section rewrites or `write_file` for a full rewrite. Never touch code blocks, identifiers, or quoted errors (see Untouchables).
|
||||
3. **Check mode.** The user asks you to audit text for STE compliance instead of rewriting it. Report each violation as rule number + offending text + compliant rewrite, using `references/checklist.md`.
|
||||
|
||||
This skill differs from `humanizer`: humanizer restores natural human voice; simple-english enforces a controlled language for technical instructions. For docs, runbooks, and error messages use this skill. For blog posts, essays, and personal writing use humanizer. Do not apply both to the same text.
|
||||
|
||||
## Your Task
|
||||
|
||||
When asked to write or rewrite technical text:
|
||||
|
||||
1. **Select the mode** (pragmatic or strict, below).
|
||||
2. **Classify each passage** as procedural or descriptive. Every other rule depends on this.
|
||||
3. **Correct your vocabulary before drafting.** In strict mode, use `make sure that` for the check/verify/confirm/ensure concept — the dictionary rejects all four as verbs. In pragmatic mode, pick one and keep it. Pick ONE noun for config/settings (all are valid technical nouns — pick one and keep it). Use no other word for these concepts in the whole document.
|
||||
4. **Apply the rules** from the catalog below.
|
||||
5. **Do the self-check** before you deliver. This step is not optional.
|
||||
6. **Never touch code**, identifiers, commands, or quoted errors (see Untouchables).
|
||||
|
||||
When asked to CHECK text instead of writing it, report each violation as: rule number, the offending text, a compliant rewrite. Cite only rule numbers that exist in this file. Do not cite rule numbers from memory: the numbering is unintuitive and models invent it (tested — an agent without this file cited "Rule 3.1: short sentences"; the real Rule 3.1 is about verb forms).
|
||||
|
||||
## Two Modes
|
||||
|
||||
| Mode | When | What you apply |
|
||||
|---|---|---|
|
||||
| **Pragmatic** (default) | Docs, READMEs, error messages — the user wants clear text | All structural rules. Domain words stay ("idempotent", "webhook"). |
|
||||
| **Strict** | The user names STE, ASD-STE100, or compliance | Structural rules + full vocabulary discipline, and tell the user that full compliance needs the official dictionary (free at asd-ste100.org). |
|
||||
|
||||
## Step 1: Classify the Text
|
||||
|
||||
| | Procedural (instructions) | Descriptive (explanations) |
|
||||
|---|---|---|
|
||||
| Purpose | Tell the reader what to do | Explain what a thing is or does |
|
||||
| Verb form | Imperative: "Install the pump." | Simple present/past/future |
|
||||
| Sentence limit | **20 words** (Rule 5.1) | **25 words** (Rule 6.3) |
|
||||
| Unit rule | One instruction per sentence (5.2) | One topic per paragraph (6.5), max six sentences per paragraph (6.6) |
|
||||
|
||||
Do not mix the two in one passage. A "Getting started" section is procedural. An "Architecture" section is descriptive. A note inside a procedure is descriptive (25-word limit, no imperative).
|
||||
|
||||
## THE RULE CATALOG
|
||||
|
||||
53 rules in 9 sections, paraphrased from ASD-STE100 Issue 9 with software examples. The official wording is in the free standard at asd-ste100.org.
|
||||
|
||||
### Section 1 — Words (Rules 1.1-1.14)
|
||||
|
||||
| Rule | Instruction |
|
||||
|---|---|
|
||||
| 1.1 | Use only approved words, technical nouns, or technical verbs. |
|
||||
| 1.2 | Use an approved word only as its listed part of speech. |
|
||||
| 1.3 | Use an approved word only with its approved meaning. |
|
||||
| 1.4 | Use only the approved forms of verbs and adjectives. |
|
||||
| 1.5 | You can use domain words as technical nouns ("webhook", "commit", "endpoint"). |
|
||||
| 1.6 | Use an unapproved word only when it is a technical noun or part of one. |
|
||||
| 1.7 | Do not use technical nouns as verbs. |
|
||||
| 1.8 | Use the technical nouns of your project or industry. |
|
||||
| 1.9 | When you pick a technical noun, pick a short and clear one. |
|
||||
| 1.10 | No regional, slang, or jargon words as technical nouns. |
|
||||
| 1.11 | One item, one name. Do not call it "config" here and "settings" there. |
|
||||
| 1.12 | You can use domain verbs as technical verbs ("deploy", "compile", "merge"). |
|
||||
| 1.13 | Do not use technical verbs as nouns. |
|
||||
| 1.14 | Use American English spelling. |
|
||||
|
||||
In pragmatic mode, rules 1.5, 1.8, and 1.12 do the heavy lifting: your domain vocabulary is legal. The ones agents break are 1.7, 1.11, and 1.13.
|
||||
|
||||
**Before:** You can webhook the event, then do a deploy.
|
||||
**After:** Send the event to the webhook. Then deploy the service.
|
||||
|
||||
### Section 2 — Multi-word nouns (Rules 2.1-2.2)
|
||||
|
||||
| Rule | Instruction |
|
||||
|---|---|
|
||||
| 2.1 | Write multi-word nouns of three words or fewer. |
|
||||
| 2.2 | When a technical noun needs more than three words, write it in full once, then give a short form or hyphenate the units. |
|
||||
|
||||
Break long noun chains with prepositions (of, on, in, for):
|
||||
|
||||
**Before:** the connection pool timeout configuration value
|
||||
**After:** the timeout value for the connection pool
|
||||
|
||||
### Section 3 — Verbs (Rules 3.1-3.7)
|
||||
|
||||
| Rule | Instruction |
|
||||
|---|---|
|
||||
| 3.1 | Use only the verb forms that the dictionary gives. |
|
||||
| 3.2 | Use only: infinitive, imperative, simple present, simple past, simple future, past participle as adjective. |
|
||||
| 3.3 | Use the past participle only as an adjective ("the cached response"). |
|
||||
| 3.4 | No auxiliary verbs for complex constructions. No present perfect, no "is to be installed". |
|
||||
| 3.5 | Use an "-ing" form only as a technical noun or inside one ("logging", "the mounting bracket") — never as a verb. |
|
||||
| 3.6 | Active voice. In descriptive text, passive is legal only when the agent is unknown. |
|
||||
| 3.7 | Describe an action with a verb, not a noun ("compress the file", not "perform compression of the file"). |
|
||||
|
||||
**Approved modals: can, will, must. Banned: should, would, may, might, could (Rule 3.2).**
|
||||
The standard rejects "could" even for possibility: write "an explosion can occur", never "could occur". For "should": a requirement becomes "must"; a suggestion is stated as fact or deleted. This matters double for agent instructions — models read "should" as optional.
|
||||
|
||||
**Before:** The migration has completed and the table is being rebuilt.
|
||||
**After:** The migration is complete. The database rebuilds the table.
|
||||
|
||||
**Before:** The flag can be set in the config file, making restarts unnecessary.
|
||||
**After:** You can set the flag in the config file. Then a restart is not necessary.
|
||||
|
||||
**Before:** The temperature must be adjusted.
|
||||
**After:** Adjust the temperature.
|
||||
|
||||
### Section 4 — Sentences (Rules 4.1-4.5)
|
||||
|
||||
| Rule | Instruction |
|
||||
|---|---|
|
||||
| 4.1 | Write short and clear sentences. |
|
||||
| 4.2 | Do not omit words or use contractions to shorten sentences. Keep articles, keep "that". |
|
||||
| 4.3 | Use a vertical list for complex text. |
|
||||
| 4.4 | Use connecting words between sentences on related topics ("Then", "As a result"). |
|
||||
| 4.5 | Put an article (the, a, an) or a demonstrative adjective (this, these) before nouns where applicable. |
|
||||
|
||||
Rule 4.2 is the anti-terseness rule. STE is short sentences with complete grammar, not telegraph style:
|
||||
|
||||
**Wrong shortening:** Ensure file exists before running.
|
||||
**STE:** Make sure that the file exists before you run the command.
|
||||
|
||||
### Section 5 — Procedural writing (Rules 5.1-5.5)
|
||||
|
||||
| Rule | Instruction |
|
||||
|---|---|
|
||||
| 5.1 | Maximum 20 words per sentence. Warnings and cautions included. |
|
||||
| 5.2 | One instruction per sentence, unless two actions happen at the same time. |
|
||||
| 5.3 | Write instructions in the imperative: "Run the migration." |
|
||||
| 5.4 | Put a required condition before the command, divided by a comma: "If the build fails, read the log." |
|
||||
| 5.5 | Notes give information, never instructions. Notes get the 25-word limit. |
|
||||
|
||||
**Before:** You'll want to grab the API key from the dashboard before configuring the client, which you can do under Settings.
|
||||
**After:** Get the API key from the dashboard, under Settings. Then configure the client with this key.
|
||||
|
||||
### Section 6 — Descriptive writing (Rules 6.1-6.6)
|
||||
|
||||
| Rule | Instruction |
|
||||
|---|---|
|
||||
| 6.1 | Give information gradually: one new fact per sentence. |
|
||||
| 6.2 | Use key words and phrases to give the text a logical structure. |
|
||||
| 6.3 | Maximum 25 words per sentence. |
|
||||
| 6.4 | Group related information in paragraphs. |
|
||||
| 6.5 | One topic per paragraph. |
|
||||
| 6.6 | Maximum six sentences per paragraph. |
|
||||
|
||||
No imperative in descriptive text. Descriptions explain; procedures instruct.
|
||||
|
||||
### Section 7 — Safety instructions (Rules 7.1-7.3)
|
||||
|
||||
| Rule | Instruction |
|
||||
|---|---|
|
||||
| 7.1 | Use a word that shows the risk level ("WARNING" = injury, "CAUTION" = damage). |
|
||||
| 7.2 | Start with a clear command or condition. |
|
||||
| 7.3 | Then give the risk or the possible result. |
|
||||
|
||||
Never bury the instruction after the explanation. The pattern transfers directly to destructive CLI flags, irreversible migrations, and dangerous API options.
|
||||
|
||||
**Before:** Note that data loss may occur in some circumstances if the destructive flag happens to be enabled when running against production.
|
||||
**After:** CAUTION: Do not use the `--force` flag against production. The flag deletes rows that do not match the source.
|
||||
|
||||
### Section 8 — Punctuation and word count (Rules 8.1-8.7)
|
||||
|
||||
| Rule | Instruction |
|
||||
|---|---|
|
||||
| 8.1 | All standard punctuation is legal except the semicolon. Write two sentences instead. |
|
||||
| 8.2 | Use hyphens to connect words that act as one unit. |
|
||||
| 8.3 | Parentheses are legal for references, item numbers, abbreviations, plural forms, explanations, alternatives. |
|
||||
| 8.4 | In a vertical list, the lead-in colon ends a sentence for word count. |
|
||||
| 8.5 | Text inside parentheses counts as one word. |
|
||||
| 8.6 | Count as one word each: numbers, numbers with units, abbreviations, alphanumeric identifiers, quoted text, titles, labels, proper nouns. |
|
||||
| 8.7 | A hyphenated word counts as one word. |
|
||||
|
||||
Rule 8.6 matters for software text: `sqlpipe run --config sqlpipe.yaml` in backticks is quoted text and counts as one word. Long identifiers do not blow your sentence budget.
|
||||
|
||||
### Section 9 — Writing practices (Rules 9.1-9.4, GR-1 to GR-8)
|
||||
|
||||
| Rule | Instruction |
|
||||
|---|---|
|
||||
| 9.1 | When a word-for-word replacement does not work, restructure the sentence. |
|
||||
| 9.2 | Use each approved word correctly: approved meaning, approved part of speech. |
|
||||
| 9.3 | Do not build phrasal verbs ("go down" → "decrease", "set up" → "install" or "configure"). |
|
||||
| 9.4 | Keep one consistent style and terminology through the whole document. |
|
||||
|
||||
General recommendations GR-1 to GR-8: keep the conjunction "that", be careful with "with", give pronouns clear referents, prefer "this + noun" over bare "this", avoid false friends, avoid Latin abbreviations, use inclusive language, and use the possessive apostrophe form only when you are sure it is correct (GR-8: if unsure, do not use it — non-native readers find it hard).
|
||||
|
||||
GR-6 for software docs: "e.g." → "for example", "i.e." → "that is", and delete "etc." — name the items or write "and more".
|
||||
|
||||
## VOCABULARY DISCIPLINE
|
||||
|
||||
The official dictionary (~900 approved words, ~1,200 banned words with alternatives) is copyrighted by ASD and is not reproduced here. Its mechanics apply without it: **one word, one meaning, one part of speech.**
|
||||
|
||||
Known part-of-speech rulings, useful as patterns:
|
||||
|
||||
| Word | Ruling |
|
||||
|---|---|
|
||||
| test, check, work | Noun only. "Do a test", not "test the pump". "Check that X" becomes "make sure that X". |
|
||||
| oil | Technical noun (TN) only. For the verb, the dictionary gives "lubricate": "Lubricate the linkage with oil." |
|
||||
| help | Verb only. For the noun, the dictionary gives "aid": "with the aid of". |
|
||||
| fall (noun) | Rejected. Use "decrease" for a reduction in value. Use FALL (verb) only for physical movement downward by gravity: "Make sure that the tools do not fall into the engine." |
|
||||
| follow | "To come after" only, never "obey". Write "obey the instructions". |
|
||||
| above, below | Physical positions only. For limits write "more than", "less than". |
|
||||
|
||||
### The modal ladder
|
||||
|
||||
| You wrote | STE writes |
|
||||
|---|---|
|
||||
| should (requirement) | must |
|
||||
| should (recommendation) | Delete it, or state it as fact: "X is better because Y." |
|
||||
| may / might / could (possibility) | can |
|
||||
| may (permission) | can |
|
||||
| would (hypothetical) | Restructure: "If X occurs, Y occurs." |
|
||||
|
||||
### Slop-to-simple substitutions
|
||||
|
||||
This table is ours, not the ASD dictionary. It maps the words AI-generated docs overuse to plain replacements. If the word carries no fact, delete it instead of replacing it.
|
||||
|
||||
| Slop | Write instead |
|
||||
|---|---|
|
||||
| leverage, utilize | use |
|
||||
| in order to | to |
|
||||
| prior to | before |
|
||||
| ensure | make sure that (strict mode; in pragmatic mode, ensure is an allowed pick if it is your one chosen check-verb) |
|
||||
| it is worth noting that | (delete) |
|
||||
| it's important to, crucially | (delete — state the fact) |
|
||||
| simply, just, easily, seamlessly, effortlessly | (delete) |
|
||||
| robust, powerful, comprehensive, performant | (delete, or give the measurable property) |
|
||||
| functionality | function, feature |
|
||||
| enables you to, allows you to | you can |
|
||||
| is designed to, aims to | (delete — say what it does) |
|
||||
| facilitate | help, make possible |
|
||||
| dive into, delve into | read, examine |
|
||||
| when it comes to | for |
|
||||
| in the event that | if |
|
||||
| due to the fact that | because |
|
||||
| as needed, as necessary | (state the condition) |
|
||||
| and/or | Pick one, or write "X, or Y, or both" |
|
||||
| e.g. / i.e. / etc. | for example / that is / (name the items) |
|
||||
| gracefully handles | (say what it does: "retries three times, then stops") |
|
||||
| out of the box | by default |
|
||||
| under the hood | internally |
|
||||
| blazingly fast, state-of-the-art | fast (give the number) / (delete) |
|
||||
| streamline | make simpler, make faster |
|
||||
| plethora, myriad | many |
|
||||
| addresses the issue, tackles | corrects the fault, removes the error |
|
||||
|
||||
### Consistency pass
|
||||
|
||||
Collapse synonym rotations to one term each (Rules 1.11, 9.4). The two lists below work differently.
|
||||
|
||||
**Technical nouns — not in the dictionary. Pick one and keep it consistent (both modes):**
|
||||
|
||||
- config / configuration / settings / options → pick one
|
||||
|
||||
**Dictionary rulings — the standard has already chosen. Use the approved word (strict mode); pick one and keep it consistent (pragmatic mode):**
|
||||
|
||||
| You wrote | Dictionary status | Use instead |
|
||||
|---|---|---|
|
||||
| check (verb) / verify / confirm / ensure | All rejected as verbs | `make sure that` (strict); pick one (pragmatic) |
|
||||
| validate | Not in dictionary | Use as technical verb (Rule 1.12), or replace with `make sure that` |
|
||||
| delete / drop (verb) / destroy | All rejected | `erase` (data), `remove` (physical); avoid `drop` and `destroy` |
|
||||
| remove | Approved verb | Keep it |
|
||||
| run / execute | Both rejected | `operate` for run, `do` for execute (strict); pick one (pragmatic) |
|
||||
| invoke / launch | Not in dictionary | Use as technical verbs (Rule 1.12) |
|
||||
| display (verb) / render / present (verb) | All rejected | `show` (approved verb) |
|
||||
| issue | Not in dictionary | Use as technical noun, or replace with `problem` (approved) |
|
||||
| failure | Rejected in general use; approved as TN for performance loss | Use only when it means a performance error: "a failure of the pump" |
|
||||
| error | Approved noun | Keep it |
|
||||
| problem | Approved noun | Keep it |
|
||||
|
||||
## Untouchables
|
||||
|
||||
These are technical names (Rules 1.5, 8.6). Leave them exact, even when they break vocabulary rules:
|
||||
|
||||
- Code blocks, inline code, identifiers, CLI commands, flags, file paths
|
||||
- Quoted error messages and log lines
|
||||
- Product names, API endpoint names, config keys
|
||||
- Numbers with units — each counts as one word in the sentence limit
|
||||
|
||||
## Beyond Documentation
|
||||
|
||||
Same rules, different targets. Full adaptations in `references/use-cases.md`:
|
||||
|
||||
- **Error messages**: state what happened (simple past), the cause if known, then the fix as an imperative. No "Oops", no "Please ensure", no apology filler.
|
||||
- **Runbooks**: STE's home turf. Imperative steps, conditions first, warnings before the step.
|
||||
- **Incident reports**: simple past only. "We have identified an issue that may have impacted" becomes "Between 14:02 and 14:31 UTC, 12% of requests failed."
|
||||
- **Release notes**: breaking changes follow the warning pattern — command first, risk second.
|
||||
- **Agent instructions (prompts, AGENTS.md)**: a system prompt is a procedure for a reader that cannot ask questions. One instruction per sentence, no "should", condition first.
|
||||
- **Translation prep**: STE's original job. One meaning per word plus complete grammar removes most translation ambiguity.
|
||||
|
||||
## Self-Check Before You Deliver
|
||||
|
||||
This step is not optional. Run these four checks on your draft:
|
||||
|
||||
1. Count words in your three longest sentences. Over the 20/25 limit → split them.
|
||||
2. Search your draft for: `'ll`, `'re`, `'s` (contraction), `has been`, `have been`, `should`, `-ing` verbs after a comma, semicolons.
|
||||
3. Search for every `if` and `when`. Each one stands at the START of its sentence, before the command. "Increase the timeout if the network is slow" → "If the network is slow, increase the timeout."
|
||||
4. Search for the verbs you did NOT pick in Your Task step 3 (the check/verify/confirm set). Replace every hit with your chosen verb.
|
||||
|
||||
Fix what you find, then deliver. For a full audit, run `references/checklist.md`.
|
||||
|
||||
## Full Example
|
||||
|
||||
**Before (real unedited AI output):**
|
||||
|
||||
> **Connection timeouts.** If sqlpipe hangs or fails with `dial tcp: i/o timeout`, check that the host running sqlpipe can reach the Postgres port (usually 5432) — this is often a security group or firewall rule blocking the connection. If you're connecting to a managed database (RDS, Cloud SQL, etc.), confirm the instance allows connections from sqlpipe's IP. You can also try increasing `source.connect_timeout_seconds` in your config, since a slow network path can trip the default timeout even when the connection eventually succeeds.
|
||||
|
||||
**After (classified procedural, verb = "make sure", conditions first, one instruction per sentence):**
|
||||
|
||||
> **Connection timeouts.** sqlpipe stops with `dial tcp: i/o timeout` when it cannot reach the Postgres port (5432 by default).
|
||||
>
|
||||
> 1. Make sure that the host that runs sqlpipe can reach the Postgres port. A firewall or security group usually blocks it.
|
||||
> 2. If the database is managed (RDS, Cloud SQL), make sure that the instance accepts connections from the IP of sqlpipe.
|
||||
> 3. If the network is slow, increase `source.connect_timeout_seconds` in the configuration.
|
||||
|
||||
What changed: 40-word sentences split under 20; "you're" expanded; "check/confirm" collapsed to "make sure that"; every condition moved before its command; "etc." removed; code and error strings untouched.
|
||||
|
||||
## Limits
|
||||
|
||||
STE is for technical facts and instructions. Do not apply it to marketing copy, blog voice, or brand writing — it deletes persuasion by design. When a user asks for STE on marketing text, say so and offer it for the docs instead.
|
||||
|
||||
This skill is an unofficial aid. It is not affiliated with or endorsed by ASD or STEMG, and no tool can guarantee STE compliance. ASD-STE100 is a registered trademark of ASD. The official standard is a free download at asd-ste100.org.
|
||||
|
||||
## References
|
||||
|
||||
- `references/checklist.md` — full verification pass with searchable patterns, for check mode and final audits
|
||||
- `references/use-cases.md` — long-form adaptations: error messages, runbooks, incident reports, commits, UI copy, i18n
|
||||
@@ -0,0 +1,240 @@
|
||||
---
|
||||
title: "Sketch — Throwaway HTML mockups: 2-3 design variants to compare"
|
||||
sidebar_label: "Sketch"
|
||||
description: "Throwaway HTML mockups: 2-3 design variants to compare"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Sketch
|
||||
|
||||
Throwaway HTML mockups: 2-3 design variants to compare.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/sketch` |
|
||||
| Path | `optional-skills/creative\sketch` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Hermes Agent (adapted from gsd-build/get-shit-done) |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `sketch`, `mockup`, `design`, `ui`, `prototype`, `html`, `variants`, `exploration`, `wireframe`, `comparison` |
|
||||
| Related skills | [`spike`](/docs/user-guide/skills/bundled/software-development/software-development-spike), [`claude-design`](/docs/user-guide/skills/bundled/creative/creative-claude-design), [`popular-web-designs`](/docs/user-guide/skills/bundled/creative/creative-popular-web-designs), [`excalidraw`](/docs/user-guide/skills/optional/creative/creative-excalidraw) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Sketch
|
||||
|
||||
Use this skill when the user wants to **see a design direction before committing** to one — exploring a UI/UX idea as disposable HTML mockups. The point is to generate 2-3 interactive variants so the user can compare visual directions side-by-side, not to produce shippable code.
|
||||
|
||||
Load this when the user says things like "sketch this screen", "show me what X could look like", "compare layout A vs B", "give me 2-3 takes on this UI", "let me see some variants", "mockup this before I build".
|
||||
|
||||
## When NOT to use this
|
||||
|
||||
- User wants a production component — use `claude-design` or build it properly
|
||||
- User wants a polished one-off HTML artifact (landing page, deck) — `claude-design`
|
||||
- User wants a diagram — `excalidraw`, `architecture-diagram`
|
||||
- The design is already locked — just build it
|
||||
|
||||
## If the user has the full GSD system installed
|
||||
|
||||
If `gsd-sketch` shows up as a sibling skill (installed via `npx get-shit-done-cc --hermes`), you can use **`gsd-sketch`** for the fuller workflow: persistent `.planning/sketches/` with MANIFEST, frontier mode analysis, consistency audits across past sketches, and integration with the rest of GSD. This skill is the lightweight standalone version — one-off sketching without the state machinery.
|
||||
|
||||
> **Note:** The upstream GSD project ([gsd-build/get-shit-done](https://github.com/gsd-build/get-shit-done)) is **archived / no longer maintained** on GitHub. The npm package (`get-shit-done-cc`) still installs, but treat it as an archived community project — this standalone `sketch` skill is the maintained path and needs nothing extra.
|
||||
|
||||
## Core method
|
||||
|
||||
```
|
||||
intake → variants → head-to-head → pick winner (or iterate)
|
||||
```
|
||||
|
||||
### 1. Intake (skip if the user already gave you enough)
|
||||
|
||||
Before generating variants, get three things — one question at a time, not all at once:
|
||||
|
||||
1. **Feel.** "What should this feel like? Adjectives, emotions, a vibe." — *"calm, editorial, like Linear"* tells you more than *"minimal"*.
|
||||
2. **References.** "What apps, sites, or products capture the feel you're imagining?" — actual references beat abstract descriptions.
|
||||
3. **Core action.** "What's the single most important thing a user does on this screen?" — the variants should all serve this well; if they don't, they're just decoration.
|
||||
|
||||
Reflect each answer briefly before the next question. If the user already gave you all three upfront, skip straight to variants.
|
||||
|
||||
### 2. Variants (2-3, never 1, rarely 4+)
|
||||
|
||||
Produce **2-3 variants** in one go. Each variant is a complete, standalone HTML file. Don't describe variants — build them. The point is comparison.
|
||||
|
||||
Each variant should take a **different design stance**, not different pixel values. Three good variant axes:
|
||||
|
||||
- **Density:** compact / airy / ultra-dense (pick two contrasting poles)
|
||||
- **Emphasis:** content-first / action-first / tool-first
|
||||
- **Aesthetic:** editorial / utilitarian / playful
|
||||
- **Layout:** single-column / sidebar / split-pane
|
||||
- **Grounding:** card-based / bare-content / document-style
|
||||
|
||||
Pick one axis and pull apart from it. Two variants that differ only in accent color are wasted effort — the user can't distinguish them.
|
||||
|
||||
**Variant naming:** describe the stance, not the number.
|
||||
|
||||
<!-- ascii-guard-ignore -->
|
||||
```
|
||||
sketches/
|
||||
├── 001-calm-editorial/
|
||||
│ ├── index.html
|
||||
│ └── README.md
|
||||
├── 001-utilitarian-dense/
|
||||
│ ├── index.html
|
||||
│ └── README.md
|
||||
└── 001-playful-split/
|
||||
├── index.html
|
||||
└── README.md
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
### 3. Make them real HTML
|
||||
|
||||
Each variant is a **single self-contained HTML file**:
|
||||
|
||||
- Inline `<style>` — no build step, no external CSS
|
||||
- System fonts or one Google Font via `<link>`
|
||||
- Tailwind via CDN (`<script src="https://cdn.tailwindcss.com"></script>`) is fine
|
||||
- Realistic fake content — actual sentences, actual names, not "Lorem ipsum"
|
||||
- **Interactive**: links clickable, hovers real, at least one state transition (open/close, filter, toggle). A frozen static image is a worse spike than a sloppy animated one.
|
||||
|
||||
Open it in a browser. If it looks broken, fix it before showing the user.
|
||||
|
||||
**Verify variants visually — use Hermes' browser tools.** Don't just write HTML and hope it renders; load each variant and look at it:
|
||||
|
||||
```
|
||||
browser_navigate(url="file:///absolute/path/to/sketches/001-calm-editorial/index.html")
|
||||
browser_vision(question="Does this layout look clean and readable? Any visible bugs (overlapping text, unstyled elements, broken images)?")
|
||||
```
|
||||
|
||||
`browser_vision` returns an AI description of what's actually on the page plus a screenshot path — catches layout bugs that pure source inspection misses (e.g. a font import that silently failed, a flex container that collapsed). Fix and re-navigate until each variant looks right.
|
||||
|
||||
**Default CSS reset + system font stack** for fast starts:
|
||||
|
||||
```html
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
"Helvetica Neue", Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
color: #1a1a1a;
|
||||
background: #fafafa;
|
||||
line-height: 1.5;
|
||||
}
|
||||
</style>
|
||||
```
|
||||
|
||||
### 4. Variant README
|
||||
|
||||
Each variant's `README.md` answers:
|
||||
|
||||
```markdown
|
||||
## Variant: {stance name}
|
||||
|
||||
### Design stance
|
||||
One sentence on the principle driving this variant.
|
||||
|
||||
### Key choices
|
||||
- Layout: ...
|
||||
- Typography: ...
|
||||
- Color: ...
|
||||
- Interaction: ...
|
||||
|
||||
### Trade-offs
|
||||
- Strong at: ...
|
||||
- Weak at: ...
|
||||
|
||||
### Best for
|
||||
- The kind of user or use case this variant actually serves
|
||||
```
|
||||
|
||||
### 5. Head-to-head
|
||||
|
||||
After all variants are built, present them as a comparison. Don't just list — **opinionate**:
|
||||
|
||||
```markdown
|
||||
## Three takes on the home screen
|
||||
|
||||
| Dimension | Calm editorial | Utilitarian dense | Playful split |
|
||||
|-----------|----------------|-------------------|---------------|
|
||||
| Density | Low | High | Medium |
|
||||
| Primary action visibility | Low | High | Medium |
|
||||
| Scan-ability | High | Medium | Low |
|
||||
| Feel | Calm, trusted | Sharp, tool-like | Inviting, energetic |
|
||||
|
||||
**My take:** Utilitarian dense for power users, calm editorial for content-forward audiences. Playful split is weakest — tries to do both and commits to neither.
|
||||
```
|
||||
|
||||
Let the user pick a winner, or combine two into a hybrid, or ask for another round.
|
||||
|
||||
## Theming (when the project has a visual identity)
|
||||
|
||||
If the user has an existing theme (colors, fonts, tokens), put shared tokens in `sketches/themes/tokens.css` and `@import` them in each variant. Keep tokens minimal:
|
||||
|
||||
```css
|
||||
/* sketches/themes/tokens.css */
|
||||
:root {
|
||||
--color-bg: #fafafa;
|
||||
--color-fg: #1a1a1a;
|
||||
--color-accent: #0066ff;
|
||||
--color-muted: #666;
|
||||
--radius: 8px;
|
||||
--font-display: "Inter", sans-serif;
|
||||
--font-body: -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
}
|
||||
```
|
||||
|
||||
Don't over-tokenize a throwaway sketch — three colors and one font is usually enough.
|
||||
|
||||
## Interactivity bar
|
||||
|
||||
A sketch is interactive enough when the user can:
|
||||
|
||||
1. **Click a primary action** and something visible happens (state change, modal, toast, navigation feint)
|
||||
2. **See one meaningful state transition** (filter a list, toggle a mode, open/close a panel)
|
||||
3. **Hover recognizable affordances** (buttons, rows, tabs)
|
||||
|
||||
More than that is over-engineering a throwaway. Less than that is a screenshot.
|
||||
|
||||
## Frontier mode (picking what to sketch next)
|
||||
|
||||
If sketches already exist and the user says "what should I sketch next?":
|
||||
|
||||
- **Consistency gaps** — two winning variants from different sketches made independent choices that haven't been composed together yet
|
||||
- **Unsketched screens** — referenced but never explored
|
||||
- **State coverage** — happy path sketched, but not empty / loading / error / 1000-items
|
||||
- **Responsive gaps** — validated at one viewport; does it hold at mobile / ultrawide?
|
||||
- **Interaction patterns** — static layouts exist; transitions, drag, scroll behavior don't
|
||||
|
||||
Propose 2-4 named candidates. Let the user pick.
|
||||
|
||||
## Output
|
||||
|
||||
- Create `sketches/` (or `.planning/sketches/` if the user is using GSD conventions) in the repo root
|
||||
- One subdir per variant: `NNN-stance-name/index.html` + `README.md`
|
||||
- Tell the user how to open them: `open sketches/001-calm-editorial/index.html` on macOS, `xdg-open` on Linux, `start` on Windows
|
||||
- Keep variants disposable — a sketch that you felt the need to preserve should be promoted into real project code, not curated as an asset
|
||||
|
||||
**Typical tool sequence for one variant:**
|
||||
|
||||
```
|
||||
terminal("mkdir -p sketches/001-calm-editorial")
|
||||
write_file("sketches/001-calm-editorial/index.html", "<!doctype html>...")
|
||||
write_file("sketches/001-calm-editorial/README.md", "## Variant: Calm editorial\n...")
|
||||
browser_navigate(url="file://$(pwd)/sketches/001-calm-editorial/index.html")
|
||||
browser_vision(question="How does this look? Any obvious layout issues?")
|
||||
```
|
||||
|
||||
Repeat for each variant, then present the comparison table.
|
||||
|
||||
## Attribution
|
||||
|
||||
Adapted from the GSD (Get Shit Done) project's `/gsd-sketch` workflow — MIT © 2025 Lex Christopherson ([gsd-build/get-shit-done](https://github.com/gsd-build/get-shit-done)). The upstream GSD repo is now **archived/unmaintained** on GitHub; the `get-shit-done-cc` npm package still installs (`npx get-shit-done-cc --hermes --global`) and ships persistent sketch state, theme/variant pattern references, and consistency-audit workflows, but treat it as an archived community project.
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
---
|
||||
title: "Social Media Content Calendar — Plan multi-platform social campaigns: briefs to posting"
|
||||
sidebar_label: "Social Media Content Calendar"
|
||||
description: "Plan multi-platform social campaigns: briefs to posting"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Social Media Content Calendar
|
||||
|
||||
Plan multi-platform social campaigns: briefs to posting.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/social-media-content-calendar` |
|
||||
| Path | `optional-skills/creative\social-media-content-calendar` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | Ben Barclay (benbarclay), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Social-Media`, `Content-Calendar`, `Campaigns`, `Publishing` |
|
||||
| Related skills | [`xurl`](/docs/user-guide/skills/bundled/social-media/social-media-xurl), [`humanizer`](/docs/user-guide/skills/bundled/creative/creative-humanizer) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Social Media Content Calendar
|
||||
|
||||
Plan a concrete calendar across selected social platforms. This skill owns campaign structure, post briefs, channel adaptation, approvals, and publishing verification; platform skills such as `xurl` own API commands. For platforms without a connector, the verified handoff ends at approved drafts for the user's scheduler — say so rather than claiming publication.
|
||||
|
||||
## When to Use
|
||||
|
||||
- "Build next month's social calendar."
|
||||
- "Turn this launch into posts for X, LinkedIn, Instagram, and TikTok."
|
||||
- "Draft and schedule a campaign."
|
||||
- "Repurpose these articles/videos into social content."
|
||||
|
||||
Don't use for: single one-off posts (use the platform skill directly).
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Define campaign constraints
|
||||
|
||||
Record objective, audience, offer/message, platforms, date range, cadence, voice, mandatory/prohibited claims, links, tracking convention, localization, and approval/publishing authority. Done when each proposed post has a clear business purpose.
|
||||
|
||||
### 2. Inventory source material
|
||||
|
||||
Collect verified product facts, launches, articles, media, testimonials with permission, brand assets, and key dates using `read_file` and `web_extract`. Mark claim owners and expiration. Done when unsupported claims and missing assets are visible.
|
||||
|
||||
### 3. Build themes and calendar slots
|
||||
|
||||
Create a balanced mix such as education, proof, product, community, event, behind-the-scenes, and conversation. Account for platform cadence and campaign milestones. Done when dates, platforms, themes, and objectives form a coherent calendar rather than duplicate cross-posts.
|
||||
|
||||
### 4. Write platform-specific briefs
|
||||
|
||||
For each post specify hook, core message, format, copy length, CTA, link, asset dimensions/content, accessibility text, tags/mentions, and success metric. Adapt rather than copy-paste between platforms. Done when a creator can produce the asset without hidden context.
|
||||
|
||||
### 5. Draft copy and assets
|
||||
|
||||
Load `humanizer` for voice; generate visuals with the `image_generate` tool where assets are needed. Preserve factual claims and shared campaign identity while respecting platform norms. Done when every calendar slot has draft copy and asset status.
|
||||
|
||||
### 6. Run editorial and risk review
|
||||
|
||||
Check factual accuracy, tone, repetition, rights/permissions, accessibility, disclosures, link destination, date relevance, and crisis sensitivity. Mark `draft`, `needs review`, or `approved`; do not publish from draft. Done when every post has a disposition and owner.
|
||||
|
||||
### 7. Schedule or hand off
|
||||
|
||||
Present the approval batch. Publish/schedule only approved posts using available platform skills (`xurl` for X); for platforms without a connector, deliver the approved package (copy, assets, timing) for the user's scheduling tool and mark those slots handed-off, not published. Read back scheduled time, account, content preview, and provider post/job ID for anything actually published. Done when the calendar reflects verified publishing or handoff status per slot.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Identical copy on every platform.
|
||||
- Filling cadence with low-value repetitive posts.
|
||||
- Publishing unverified metrics, testimonials, or future claims.
|
||||
- Confusing generated asset completion with scheduled publication.
|
||||
- Claiming "scheduled" for platforms where the handoff ended at drafts.
|
||||
|
||||
## Verification
|
||||
|
||||
- [ ] Every post traces to a campaign objective and a verified claim inventory.
|
||||
- [ ] No post was published from `draft` or `needs review` state.
|
||||
- [ ] Published slots have provider-confirmed IDs; handed-off slots are marked as such.
|
||||
- [ ] Rights, permissions, and disclosures checked before any publish.
|
||||
@@ -0,0 +1,294 @@
|
||||
---
|
||||
title: "Tldraw Offline — Drive and script tldraw offline canvases with an agent"
|
||||
sidebar_label: "Tldraw Offline"
|
||||
description: "Drive and script tldraw offline canvases with an agent"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Tldraw Offline
|
||||
|
||||
Drive and script tldraw offline canvases with an agent.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/tldraw-offline` |
|
||||
| Path | `optional-skills/creative\tldraw-offline` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Teknium + Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `tldraw`, `canvas`, `whiteboard`, `document-script`, `diagramming` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# tldraw offline Skill
|
||||
|
||||
Work with the tldraw offline desktop app (offline.tldraw.com): read the open
|
||||
canvas, make edits, and write **document scripts** — JavaScript embedded in a
|
||||
`.tldraw` file that runs on load and gives the file durable behavior. The app
|
||||
runs a **local HTTP API** (default `localhost:7236`) that a coding agent drives
|
||||
with plain `curl` from its terminal — this is exactly how the app's own homepage
|
||||
demo (Codex editing a canvas live) works. The agent does NOT use computer-use /
|
||||
GUI clicking, and does NOT hand-edit the `.tldraw` file directly. Keep tldraw
|
||||
offline open while you work.
|
||||
|
||||
## When to Use
|
||||
|
||||
- The user has tldraw offline open and asks you to build or modify a canvas
|
||||
(diagrams, wireframes, layouts).
|
||||
- You want to add durable behavior to a drawing (reactive shapes, interactive
|
||||
buttons, animation, connection logic) via an embedded document script.
|
||||
|
||||
Do NOT hand-place shapes to imitate a drawing — write the code that generates
|
||||
them. Agents are far better at scripting the canvas than at drawing on it.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **tldraw offline installed and running**, with a document open. Releases:
|
||||
https://github.com/tldraw/tldraw-offline/releases/latest (macOS DMG, Windows
|
||||
x64/Arm64, Linux `x86_64`/`arm64` AppImage or amd64/arm64 `.deb`).
|
||||
- **Agent skills installed in the app**: `Develop → Install Agent Skills`. The
|
||||
app writes its own tldraw skill into `~/.codex/skills/`, `~/.claude/skills/`,
|
||||
`~/.cursor/skills/`, and `~/.gemini/skills/` — teaching that agent the `curl`
|
||||
recipes below. (This Hermes skill mirrors that guidance for Hermes.)
|
||||
- **The local control API.** On launch the app writes `server.json` to its config
|
||||
dir (Linux `~/.config/tldraw/`, macOS `~/Library/Application Support/tldraw/`,
|
||||
Windows `%APPDATA%\tldraw\`) with `port` (default `7236`), a bearer `token`,
|
||||
`pid`, and `startedAt`. Every request except `GET /` needs
|
||||
`Authorization: Bearer <token>`. A clean quit removes `server.json`; if it's
|
||||
present but the port doesn't answer, the app quit uncleanly — treat as not
|
||||
running.
|
||||
- **Re-read port + token on EVERY shell call.** Each terminal call is a fresh
|
||||
shell, so an `export`ed token does not persist — "export once and reuse" sends
|
||||
an empty token and 401s. Read both inline at the top of each call:
|
||||
`PORT=$(jq -r .port <server.json>); TOKEN=$(jq -r .token <server.json>)`.
|
||||
- No account or network needed for local editing.
|
||||
|
||||
## How to Run
|
||||
|
||||
Two distinct workflows. Pick by whether the change must survive a reload.
|
||||
|
||||
**A. One-off canvas edits (`/exec`)** — layout, generating shapes, cleanup. This
|
||||
is a live edit, not saved script:
|
||||
|
||||
```bash
|
||||
BASE=http://localhost:7236
|
||||
TOKEN=$(python -c "import json;print(json.load(open('$HOME/.config/tldraw/server.json'))['token'])")
|
||||
# find the focused document id
|
||||
DOC=$(curl -s "$BASE/api/search" -X POST -H 'content-type: application/json' \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-d '{"code":"return (await api.getFocusedDoc()).id"}' | python -c "import sys,json;print(json.load(sys.stdin)['result'])")
|
||||
# run code with the live `editor` + `helpers` in scope
|
||||
curl -s "$BASE/api/doc/$DOC/exec" -X POST -H 'content-type: application/json' \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-d '{"code":"const {createShapeId,toRichText}=await import(\"tldraw\"); editor.createShape({id:createShapeId(),type:\"geo\",x:0,y:0,props:{geo:\"rectangle\",w:200,h:100,color:\"blue\",fill:\"solid\",richText:toRichText(\"hello\")}}); return editor.getCurrentPageShapes().length"}'
|
||||
```
|
||||
|
||||
**B. Durable behavior (`script/main.js`)** — reactive/interactive logic that must
|
||||
survive reload. Edit the file on disk; the app's watcher applies it:
|
||||
|
||||
```bash
|
||||
# get the live script file path for the doc
|
||||
curl -s "$BASE/api/doc/$DOC/script-workspace" -X POST \
|
||||
-H "Authorization: Bearer $TOKEN" # -> result.mainJsPath, result.isDefaultScript
|
||||
# edit result.mainJsPath with read_file / patch / write_file (see scripts/main.js)
|
||||
# then confirm the watcher applied it:
|
||||
curl -s "$BASE/api/doc/$DOC/script-status" -H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
The ready-to-adapt document script is `scripts/main.js`.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
The document-script contract (verified against the app's bundled
|
||||
`script-context.d.ts`):
|
||||
|
||||
```js
|
||||
import { createShapeId, toRichText } from 'tldraw' // primitives: import, not globals
|
||||
|
||||
export default function ({ editor, helpers, signal }) {
|
||||
editor.run(() => { // batch = one undo step
|
||||
helpers.createShapeIfMissing({ // idempotent furniture
|
||||
id: createShapeId('node-1'), type: 'geo', x: 0, y: 0,
|
||||
props: { geo: 'rectangle', w: 200, h: 100, richText: toRichText('hi') },
|
||||
})
|
||||
})
|
||||
|
||||
const stop = editor.store.listen(() => { /* react */ }) // fires the tick AFTER a commit
|
||||
signal.addEventListener('abort', () => stop()) // REQUIRED cleanup on rerun/close
|
||||
}
|
||||
```
|
||||
|
||||
- `ctx.editor` — the live `Editor` (`createShape`, `updateShape`, `deleteShapes`,
|
||||
`getCurrentPageShapes`, `getShape`, `getBindingsFromShape`, `zoomToFit`,
|
||||
`on('tick'|'event', fn)`, `run(fn, { history: 'ignore' })`).
|
||||
- `ctx.helpers` — `createShapeIfMissing`, `createShapesIfMissing`,
|
||||
`createArrowBetweenShapes(from, to, { arrowheadEnd })`, `translateShapes`,
|
||||
`onShapeTranslate(id, fn, { signal })`, `richTextToPlainText`, `boxShapes`,
|
||||
`getLints`.
|
||||
- `ctx.signal` — `AbortSignal`; attach every listener/interval teardown to it.
|
||||
- `config.js` (separate file) registers custom shape/tool/component utils and
|
||||
runs before mount; `main.js` runs against the mounted editor and reruns on save.
|
||||
|
||||
## Interactive UI (clickable buttons that drive state)
|
||||
|
||||
Drawn shapes can behave like a real app — the thing a static whiteboard can't do.
|
||||
Full example: `scripts/counter.js` (a number display + MINUS/RESET/PLUS buttons).
|
||||
|
||||
Verification boundary — read this before claiming interaction works or doesn't.
|
||||
The app's OWN agent playbook says to verify a clickable-UI script with "one
|
||||
simulated click and one state read" via `/exec` (`editor.dispatch` a pointer
|
||||
event, await a tick, read the shape's state) — NOT by driving a real mouse. By
|
||||
that standard the counter is verified: dispatched clicks stepped it
|
||||
`0 → 1 → 2 → 1 → 0`. Two caveats worth writing down:
|
||||
- **The script only runs once the app's file-watcher applies it.** On Linux that
|
||||
watcher uses inotify; a host with an exhausted `fs.inotify.max_user_instances`
|
||||
logs `inotify_add_watch ... No space left on device`, `script-status` shows
|
||||
`state: "not-watching"` / `hasEntry: false`, and the script never executes.
|
||||
This is a host limit, not a script bug — a normal desktop is unaffected.
|
||||
- **Driving the canvas with computer-use needs FOREGROUND delivery, not
|
||||
background.** cua-driver's default `background` delivery returns
|
||||
`background_unavailable` against Electron's occluded renderer — but that is the
|
||||
first rung, not a wall. cua-driver returns an `escalation: "foreground"` hint;
|
||||
set `delivery_mode: "foreground"` (pair with `bring_to_front`) and its X11 XTest
|
||||
path (`x11_xtest_fg`) clicks land — this dismisses the "Run Script" consent
|
||||
dialog and clicks the canvas. Verified by the Cua team on this exact v1.11.0
|
||||
AppImage (Linux/X11). Do NOT conclude "Electron rejects synthetic clicks" and
|
||||
give up in background mode — climb to foreground. (The real product path is
|
||||
still `/exec`, not clicks; this note is for computer-use-driven testing.)
|
||||
|
||||
The pattern:
|
||||
|
||||
```js
|
||||
export default function ({ editor, helpers, signal }) {
|
||||
// 1. Build buttons idempotently; tag each with meta so the handler finds them.
|
||||
// Give buttons a visible label AND a meta.action.
|
||||
// 2. Hit-test pointer_down in PAGE coordinates against the button bounds:
|
||||
const inside = (b, p) => p.x >= b.x && p.x <= b.x + b.w && p.y >= b.y && p.y <= b.y + b.h
|
||||
function onEvent(info) {
|
||||
if (!info || info.name !== 'pointer_down') return
|
||||
let p = null
|
||||
try { if (info.point && editor.screenToPage) p = editor.screenToPage(info.point) } catch {}
|
||||
p = p ?? editor.inputs?.currentPagePoint
|
||||
if (!p) return
|
||||
const hit = editor.getCurrentPageShapes().find(
|
||||
(s) => s.meta?.ui === 'button' &&
|
||||
inside({ x: s.x, y: s.y, w: s.props.w, h: s.props.h }, p)
|
||||
)
|
||||
if (hit) runAction(hit.meta.action) // mutate state; store it in a shape's meta
|
||||
}
|
||||
editor.on('event', onEvent)
|
||||
signal.addEventListener('abort', () => editor.off('event', onEvent)) // REQUIRED
|
||||
}
|
||||
```
|
||||
|
||||
- Find buttons by `meta` (or visible label via `helpers.richTextToPlainText`),
|
||||
not by hard-coded coordinates.
|
||||
- **One script owns both build and read.** If the shapes are created by one code
|
||||
path (with `meta.action: 'inc'`) and the handler reads another convention
|
||||
(`meta.action === 'PLUS'`), clicks silently do nothing. Ship the buttons built
|
||||
by the same script that handles them, or ship an empty canvas so the script
|
||||
builds them fresh — never pre-bake mismatched shapes into the file's db.
|
||||
- Keep app state in a shape's `meta` (e.g. `meta.count`) and render it as that
|
||||
shape's `richText` label, so it survives save and is readable for verification.
|
||||
- **Detach the listener on `signal` abort.** Skipping this is not cosmetic: on
|
||||
the next save the old `onEvent` stays attached alongside the new one, so every
|
||||
click fires twice and a counter jumps by 2 instead of 1.
|
||||
- For continuous motion use `editor.on('tick', fn)`; for a moving anchor with
|
||||
attached pieces use `helpers.onShapeTranslate(id, fn, { signal })`.
|
||||
|
||||
### Shipping a self-running scripted `.tldraw`
|
||||
|
||||
A `.tldraw` is a zip of `metadata.json` + `session.json` + `db.sqlite` + `assets/`
|
||||
+ `script/` (only those entries are packable). For the script to auto-run without
|
||||
the "This document contains a script → Run Script" consent dialog:
|
||||
|
||||
- `metadata.json` must carry a `script` manifest: `{ "sha256": "<digest>" }`, where
|
||||
the digest is `sha256` over each sorted `script/` path as `` `${path}\0${sha256hex(bytes)}\n` ``.
|
||||
A mismatch is rejected as tampered.
|
||||
- Pre-trust the digest by adding it to `~/.tldraw/script-trust.json`
|
||||
(`{ "trusted": ["<digest>"] }`, or `$TLDRAW_SCRIPT_TRUST`). The app skips consent
|
||||
when `isScriptTrusted(digest)` is true.
|
||||
|
||||
## Procedure
|
||||
|
||||
1. Read the current token/port from `server.json`. Find the target doc with
|
||||
`api.getFocusedDoc()` (or `api.getDocs()`); name it explicitly if several are
|
||||
open.
|
||||
2. For layout/generation, use `/exec`. For durable behavior, edit
|
||||
`script/main.js` via `/script-workspace`.
|
||||
3. Make scripts idempotent: create durable shapes with `helpers.createShapeIfMissing`
|
||||
and stable `createShapeId('name')` ids. Scripts rerun on every load.
|
||||
4. Keep script-owned writes out of the user's undo stack:
|
||||
`editor.run(fn, { history: 'ignore' })` (or `helpers.translateShapes`, which
|
||||
already does).
|
||||
5. For reactivity, `editor.store.listen(cb)` and tear it down on `signal` abort.
|
||||
For interaction, `editor.on('event', h)` (hit-test `pointer_down` in page
|
||||
coords); for animation, `editor.on('tick', h)`.
|
||||
6. For a single moving anchor + attached internals, prefer
|
||||
`helpers.onShapeTranslate(anchorId, fn, { signal })` over a broad store
|
||||
listener — a broad listener can turn your own writes into feedback loops.
|
||||
|
||||
## Shape props (validated against tldraw SDK v5 schema)
|
||||
|
||||
`editor.createShape` / `createShapeIfMissing` accept partial props (shape utils
|
||||
fill defaults). When building **raw records** for a file snapshot, every prop
|
||||
below is required (run `scripts/validate_shapes.mjs`):
|
||||
|
||||
| Shape | Required props |
|
||||
|-------|----------------|
|
||||
| `note` | `richText`, `color`, `labelColor`, `size`, `font`, `align`, `verticalAlign`, `growY`, `fontSizeAdjustment`, `url`, `scale`, `textLastEditedBy` |
|
||||
| `text` | `richText`, `color`, `size`, `font`, `textAlign`, `w`, `scale`, `autoSize` |
|
||||
| `frame` | `w`, `h`, `name`, `color` |
|
||||
| `geo` | `geo`, `w`, `h`, `color`, `fill`, `richText` (+ dash/size/etc. defaulted) |
|
||||
|
||||
`richText` must be `toRichText('...')` — a bare string is rejected. `color` enum:
|
||||
`black grey light-violet violet blue light-blue yellow orange green light-green
|
||||
light-red red white`. `font` enum: `draw sans serif mono`.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **`store.listen` fires on the tick AFTER a commit, not synchronously.** If you
|
||||
write a shape and immediately read state expecting the listener to have run, it
|
||||
hasn't. Verified live: an in-turn read shows 0 fires; after one `setTimeout`
|
||||
tick it shows 1. Same reason the app notes `editor.dispatch` is async — await a
|
||||
tick before verifying.
|
||||
- **`ctx`, not globals.** The entry is `export default function ({ editor,
|
||||
helpers, signal })`. There is no bare `editor` global in a document script.
|
||||
`createShapeId` / `toRichText` / `Vec` come from `import ... from 'tldraw'`.
|
||||
- **`richText`, not `text`.** Text/note/geo labels use `richText: toRichText(s)`.
|
||||
- **Raw records need every prop; `createShape` does not.** In-app pass only the
|
||||
props you care about; a hand-built `.tldraw` snapshot needs the full set (table).
|
||||
- **Scripts rerun on every load — be idempotent.** Use `createShapeIfMissing`
|
||||
with stable ids or you duplicate content and clobber user edits.
|
||||
- **Clean up on `signal`.** `signal.addEventListener('abort', () => stop())` for
|
||||
every `store.listen` / `editor.on` / `setInterval`; the signal fires before
|
||||
rerun and on close.
|
||||
- **Keep script writes out of undo:** `editor.run(fn, { history: 'ignore' })`.
|
||||
- **`editor.on('tick')` pauses when the window is hidden** (it is a RAF loop);
|
||||
`setInterval` keeps firing but Electron throttles it to ~1/s in the background.
|
||||
- **The API needs the bearer token** from `server.json`; the port can be non-default
|
||||
(`server.listen(0)` picks one) — always read the file, don't hardcode `7236`.
|
||||
- **Only `tldraw` / `react` / `react-dom` import** — not a Node project.
|
||||
|
||||
## Verification
|
||||
|
||||
- **Shape schema (offline, no app):** `node scripts/validate_shapes.mjs` — builds
|
||||
the real tldraw schema and validates note/text/frame. Passing prints `3/3`.
|
||||
- **Live canvas edits:** after `/exec`, read back with `/api/search` →
|
||||
`api.getShapes(docId)` (returns `{ page, viewport, shapes }`) and
|
||||
`api.getBindings(docId)` (array). Confirm expected shapes/bindings exist. Grab
|
||||
`api.getScreenshot(docId)` (returns `{ filePath, ... }`) and inspect the PNG/JPEG
|
||||
with `vision_analyze`.
|
||||
- **Durable script applied:** `GET /api/doc/:id/script-status`. Success is
|
||||
`state: "applied"` (`currentDiskDigest === lastAppliedDigest === manifestSha256`,
|
||||
`pendingApply === false`, `lastApplyError === null`). If it stays `"pending"`
|
||||
after a short retry, report that instead of claiming success; `"error"` means
|
||||
the apply failed — read `errorLogPath`.
|
||||
@@ -0,0 +1,373 @@
|
||||
---
|
||||
title: "Touchdesigner Mcp — Control TouchDesigner via twozero MCP"
|
||||
sidebar_label: "Touchdesigner Mcp"
|
||||
description: "Control TouchDesigner via twozero MCP"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Touchdesigner Mcp
|
||||
|
||||
Control TouchDesigner via twozero MCP.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/touchdesigner-mcp` |
|
||||
| Path | `optional-skills/creative\touchdesigner-mcp` |
|
||||
| Version | `1.1.0` |
|
||||
| Author | kshitijk4poor |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `TouchDesigner`, `MCP`, `twozero`, `creative-coding`, `real-time-visuals`, `generative-art`, `audio-reactive`, `VJ`, `installation`, `GLSL` |
|
||||
| Related skills | [`ascii-video`](/docs/user-guide/skills/bundled/creative/creative-ascii-video), [`manim-video`](/docs/user-guide/skills/bundled/creative/creative-manim-video) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# TouchDesigner Integration (twozero MCP)
|
||||
|
||||
## CRITICAL RULES
|
||||
|
||||
1. **NEVER guess parameter names.** Call `td_get_par_info` for the op type FIRST. Your training data is wrong for TD 2025.32.
|
||||
2. **If `tdAttributeError` fires, STOP.** Call `td_get_operator_info` on the failing node before continuing.
|
||||
3. **NEVER hardcode absolute paths** in script callbacks. Use `me.parent()` / `scriptOp.parent()`.
|
||||
4. **Prefer native MCP tools over td_execute_python.** Use `td_create_operator`, `td_set_operator_pars`, `td_get_errors` etc. Only fall back to `td_execute_python` for complex multi-step logic.
|
||||
5. **Call `td_get_hints` before building.** It returns patterns specific to the op type you're working with.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Hermes Agent -> MCP (Streamable HTTP) -> twozero.tox (port 40404) -> TD Python
|
||||
```
|
||||
|
||||
36 native tools. Free plugin (no payment/license — confirmed April 2026).
|
||||
Context-aware (knows selected OP, current network).
|
||||
Hub health check: `GET http://localhost:40404/mcp` returns JSON with instance PID, project name, TD version.
|
||||
|
||||
## Setup (Automated)
|
||||
|
||||
Run the setup script to handle everything:
|
||||
|
||||
```bash
|
||||
bash "${HERMES_HOME:-$HOME/.hermes}/skills/creative/touchdesigner-mcp/scripts/setup.sh"
|
||||
```
|
||||
|
||||
The script will:
|
||||
1. Check if TD is running
|
||||
2. Download twozero.tox if not already cached
|
||||
3. Add `twozero_td` MCP server to Hermes config (if missing)
|
||||
4. Test the MCP connection on port 40404
|
||||
5. Report what manual steps remain (drag .tox into TD, enable MCP toggle)
|
||||
|
||||
### Manual steps (one-time, cannot be automated)
|
||||
|
||||
1. **Drag `~/Downloads/twozero.tox` into the TD network editor** → click Install
|
||||
2. **Enable MCP:** click twozero icon → Settings → mcp → "auto start MCP" → Yes
|
||||
3. **Restart Hermes session** to pick up the new MCP server
|
||||
|
||||
After setup, verify:
|
||||
```bash
|
||||
nc -z 127.0.0.1 40404 && echo "twozero MCP: READY"
|
||||
```
|
||||
|
||||
## Environment Notes
|
||||
|
||||
- **Non-Commercial TD** caps resolution at 1280×1280. Use `outputresolution = 'custom'` and set width/height explicitly.
|
||||
- **Codecs:** `prores` (preferred on macOS) or `mjpa` as fallback. H.264/H.265/AV1 require a Commercial license.
|
||||
- Always call `td_get_par_info` before setting params — names vary by TD version (see CRITICAL RULES #1).
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 0: Discover (before building anything)
|
||||
|
||||
```
|
||||
Call td_get_par_info with op_type for each type you plan to use.
|
||||
Call td_get_hints with the topic you're building (e.g. "glsl", "audio reactive", "feedback").
|
||||
Call td_get_focus to see where the user is and what's selected.
|
||||
Call td_get_network to see what already exists.
|
||||
```
|
||||
|
||||
No temp nodes, no cleanup. This replaces the old discovery dance entirely.
|
||||
|
||||
### Step 1: Clean + Build
|
||||
|
||||
**IMPORTANT: Split cleanup and creation into SEPARATE MCP calls.** Destroying and recreating same-named nodes in one `td_execute_python` script causes "Invalid OP object" errors. See pitfalls #11b.
|
||||
|
||||
Use `td_create_operator` for each node (handles viewport positioning automatically):
|
||||
|
||||
```
|
||||
td_create_operator(type="noiseTOP", parent="/project1", name="bg", parameters={"resolutionw": 1280, "resolutionh": 720})
|
||||
td_create_operator(type="levelTOP", parent="/project1", name="brightness")
|
||||
td_create_operator(type="nullTOP", parent="/project1", name="out")
|
||||
```
|
||||
|
||||
For bulk creation or wiring, use `td_execute_python`:
|
||||
|
||||
```python
|
||||
# td_execute_python script:
|
||||
root = op('/project1')
|
||||
nodes = []
|
||||
for name, optype in [('bg', noiseTOP), ('fx', levelTOP), ('out', nullTOP)]:
|
||||
n = root.create(optype, name)
|
||||
nodes.append(n.path)
|
||||
# Wire chain
|
||||
for i in range(len(nodes)-1):
|
||||
op(nodes[i]).outputConnectors[0].connect(op(nodes[i+1]).inputConnectors[0])
|
||||
result = {'created': nodes}
|
||||
```
|
||||
|
||||
### Step 2: Set Parameters
|
||||
|
||||
Prefer the native tool (validates params, won't crash):
|
||||
|
||||
```
|
||||
td_set_operator_pars(path="/project1/bg", parameters={"roughness": 0.6, "monochrome": true})
|
||||
```
|
||||
|
||||
For expressions or modes, use `td_execute_python`:
|
||||
|
||||
```python
|
||||
op('/project1/time_driver').par.colorr.expr = "absTime.seconds % 1000.0"
|
||||
```
|
||||
|
||||
### Step 3: Wire
|
||||
|
||||
Use `td_execute_python` — no native wire tool exists:
|
||||
|
||||
```python
|
||||
op('/project1/bg').outputConnectors[0].connect(op('/project1/fx').inputConnectors[0])
|
||||
```
|
||||
|
||||
### Step 4: Verify
|
||||
|
||||
```
|
||||
td_get_errors(path="/project1", recursive=true)
|
||||
td_get_perf()
|
||||
td_get_operator_info(path="/project1/out", detail="full")
|
||||
```
|
||||
|
||||
### Step 5: Display / Capture
|
||||
|
||||
```
|
||||
td_get_screenshot(path="/project1/out")
|
||||
```
|
||||
|
||||
Or open a window via script:
|
||||
|
||||
```python
|
||||
win = op('/project1').create(windowCOMP, 'display')
|
||||
win.par.winop = op('/project1/out').path
|
||||
win.par.winw = 1280; win.par.winh = 720
|
||||
win.par.winopen.pulse()
|
||||
```
|
||||
|
||||
## MCP Tool Quick Reference
|
||||
|
||||
**Core (use these most):**
|
||||
| Tool | What |
|
||||
|------|------|
|
||||
| `td_execute_python` | Run arbitrary Python in TD. Full API access. |
|
||||
| `td_create_operator` | Create node with params + auto-positioning |
|
||||
| `td_set_operator_pars` | Set params safely (validates, won't crash) |
|
||||
| `td_get_operator_info` | Inspect one node: connections, params, errors |
|
||||
| `td_get_operators_info` | Inspect multiple nodes in one call |
|
||||
| `td_get_network` | See network structure at a path |
|
||||
| `td_get_errors` | Find errors/warnings recursively |
|
||||
| `td_get_par_info` | Get param names for an OP type (replaces discovery) |
|
||||
| `td_get_hints` | Get patterns/tips before building |
|
||||
| `td_get_focus` | What network is open, what's selected |
|
||||
|
||||
**Read/Write:**
|
||||
| Tool | What |
|
||||
|------|------|
|
||||
| `td_read_dat` | Read DAT text content |
|
||||
| `td_write_dat` | Write/patch DAT content |
|
||||
| `td_read_chop` | Read CHOP channel values |
|
||||
| `td_read_textport` | Read TD console output |
|
||||
|
||||
**Visual:**
|
||||
| Tool | What |
|
||||
|------|------|
|
||||
| `td_get_screenshot` | Capture one OP viewer to file |
|
||||
| `td_get_screenshots` | Capture multiple OPs at once |
|
||||
| `td_get_screen_screenshot` | Capture actual screen via TD |
|
||||
| `td_navigate_to` | Jump network editor to an OP |
|
||||
|
||||
**Search:**
|
||||
| Tool | What |
|
||||
|------|------|
|
||||
| `td_find_op` | Find ops by name/type across project |
|
||||
| `td_search` | Search code, expressions, string params |
|
||||
|
||||
**System:**
|
||||
| Tool | What |
|
||||
|------|------|
|
||||
| `td_get_perf` | Performance profiling (FPS, slow ops) |
|
||||
| `td_list_instances` | List all running TD instances |
|
||||
| `td_get_docs` | In-depth docs on a TD topic |
|
||||
| `td_agents_md` | Read/write per-COMP markdown docs |
|
||||
| `td_reinit_extension` | Reload extension after code edit |
|
||||
| `td_clear_textport` | Clear console before debug session |
|
||||
|
||||
**Input Automation:**
|
||||
| Tool | What |
|
||||
|------|------|
|
||||
| `td_input_execute` | Send mouse/keyboard to TD |
|
||||
| `td_input_status` | Poll input queue status |
|
||||
| `td_input_clear` | Stop input automation |
|
||||
| `td_op_screen_rect` | Get screen coords of a node |
|
||||
| `td_click_screen_point` | Click a point in a screenshot |
|
||||
| `td_screen_point_to_global` | Convert screenshot pixel to absolute screen coords |
|
||||
|
||||
The table above covers the 32 tools used in typical creative workflows. The remaining 4 tools (`td_project_quit`, `td_test_session`, `td_dev_log`, `td_clear_dev_log`) are admin/dev-mode utilities — see `references/mcp-tools.md` for the full 36-tool reference with complete parameter schemas.
|
||||
|
||||
## Key Implementation Rules
|
||||
|
||||
**GLSL time:** No `uTDCurrentTime` in GLSL TOP. Use the Values page:
|
||||
```python
|
||||
# Call td_get_par_info(op_type="glslTOP") first to confirm param names
|
||||
td_set_operator_pars(path="/project1/shader", parameters={"value0name": "uTime"})
|
||||
# Then set expression via script:
|
||||
# op('/project1/shader').par.value0.expr = "absTime.seconds"
|
||||
# In GLSL: uniform float uTime;
|
||||
```
|
||||
|
||||
Fallback: Constant TOP in `rgba32float` format (8-bit clamps to 0-1, freezing the shader).
|
||||
|
||||
**Feedback TOP:** Use `top` parameter reference, not direct input wire. "Not enough sources" resolves after first cook. "Cook dependency loop" warning is expected.
|
||||
|
||||
**Resolution:** Non-Commercial caps at 1280×1280. Use `outputresolution = 'custom'`.
|
||||
|
||||
**Large shaders:** Write GLSL to `/tmp/file.glsl`, then use `td_write_dat` or `td_execute_python` to load.
|
||||
|
||||
**Vertex/Point access (TD 2025.32):** `point.P[0]`, `point.P[1]`, `point.P[2]` — NOT `.x`, `.y`, `.z`.
|
||||
|
||||
**Extensions:** `ext0object` format is `"op('./datName').module.ClassName(me)"` in CONSTANT mode. After editing extension code with `td_write_dat`, call `td_reinit_extension`.
|
||||
|
||||
**Script callbacks:** ALWAYS use relative paths via `me.parent()` / `scriptOp.parent()`.
|
||||
|
||||
**Cleaning nodes:** Always `list(root.children)` before iterating + `child.valid` check.
|
||||
|
||||
## Recording / Exporting Video
|
||||
|
||||
```python
|
||||
# via td_execute_python:
|
||||
root = op('/project1')
|
||||
rec = root.create(moviefileoutTOP, 'recorder')
|
||||
op('/project1/out').outputConnectors[0].connect(rec.inputConnectors[0])
|
||||
rec.par.type = 'movie'
|
||||
rec.par.file = '/tmp/output.mov'
|
||||
rec.par.videocodec = 'prores' # Apple ProRes — NOT license-restricted on macOS
|
||||
rec.par.record = True # start
|
||||
# rec.par.record = False # stop (call separately later)
|
||||
```
|
||||
|
||||
H.264/H.265/AV1 need Commercial license. Use `prores` on macOS or `mjpa` as fallback.
|
||||
Extract frames: `ffmpeg -i /tmp/output.mov -vframes 120 /tmp/frames/frame_%06d.png`
|
||||
|
||||
**TOP.save() is useless for animation** — captures same GPU texture every time. Always use MovieFileOut.
|
||||
|
||||
### Before Recording: Checklist
|
||||
|
||||
1. **Verify FPS > 0** via `td_get_perf`. If FPS=0 the recording will be empty. See pitfalls #38-39.
|
||||
2. **Verify shader output is not black** via `td_get_screenshot`. Black output = shader error or missing input. See pitfalls #8, #40.
|
||||
3. **If recording with audio:** cue audio to start first, then delay recording by 3 frames. See pitfalls #19.
|
||||
4. **Set output path before starting record** — setting both in the same script can race.
|
||||
|
||||
## Audio-Reactive GLSL (Proven Recipe)
|
||||
|
||||
### Correct signal chain (tested April 2026)
|
||||
|
||||
```
|
||||
AudioFileIn CHOP (playmode=sequential)
|
||||
→ AudioSpectrum CHOP (FFT=512, outputmenu=setmanually, outlength=256, timeslice=ON)
|
||||
→ Math CHOP (gain=10)
|
||||
→ CHOP to TOP (dataformat=r, layout=rowscropped)
|
||||
→ GLSL TOP input 1 (spectrum texture, 256x2)
|
||||
|
||||
Constant TOP (rgba32float, time) → GLSL TOP input 0
|
||||
GLSL TOP → Null TOP → MovieFileOut
|
||||
```
|
||||
|
||||
### Critical audio-reactive rules (empirically verified)
|
||||
|
||||
1. **TimeSlice must stay ON** for AudioSpectrum. OFF = processes entire audio file → 24000+ samples → CHOP to TOP overflow.
|
||||
2. **Set Output Length manually** to 256 via `outputmenu='setmanually'` and `outlength=256`. Default outputs 22050 samples.
|
||||
3. **DO NOT use Lag CHOP for spectrum smoothing.** Lag CHOP operates in timeslice mode and expands 256 samples to 2400+, averaging all values to near-zero (~1e-06). The shader receives no usable data. This was the #1 audio sync failure in testing.
|
||||
4. **DO NOT use Filter CHOP either** — same timeslice expansion problem with spectrum data.
|
||||
5. **Smoothing belongs in the GLSL shader** if needed, via temporal lerp with a feedback texture: `mix(prevValue, newValue, 0.3)`. This gives frame-perfect sync with zero pipeline latency.
|
||||
6. **CHOP to TOP dataformat = 'r'**, layout = 'rowscropped'. Spectrum output is 256x2 (stereo). Sample at y=0.25 for first channel.
|
||||
7. **Math gain = 10** (not 5). Raw spectrum values are ~0.19 in bass range. Gain of 10 gives usable ~5.0 for the shader.
|
||||
8. **No Resample CHOP needed.** Control output size via AudioSpectrum's `outlength` param directly.
|
||||
|
||||
### GLSL spectrum sampling
|
||||
|
||||
```glsl
|
||||
// Input 0 = time (1x1 rgba32float), Input 1 = spectrum (256x2)
|
||||
float iTime = texture(sTD2DInputs[0], vec2(0.5)).r;
|
||||
|
||||
// Sample multiple points per band and average for stability:
|
||||
// NOTE: y=0.25 for first channel (stereo texture is 256x2, first row center is 0.25)
|
||||
float bass = (texture(sTD2DInputs[1], vec2(0.02, 0.25)).r +
|
||||
texture(sTD2DInputs[1], vec2(0.05, 0.25)).r) / 2.0;
|
||||
float mid = (texture(sTD2DInputs[1], vec2(0.2, 0.25)).r +
|
||||
texture(sTD2DInputs[1], vec2(0.35, 0.25)).r) / 2.0;
|
||||
float hi = (texture(sTD2DInputs[1], vec2(0.6, 0.25)).r +
|
||||
texture(sTD2DInputs[1], vec2(0.8, 0.25)).r) / 2.0;
|
||||
```
|
||||
|
||||
See `references/network-patterns.md` for complete build scripts + shader code.
|
||||
|
||||
## Operator Quick Reference
|
||||
|
||||
| Family | Color | Python class / MCP type | Suffix |
|
||||
|--------|-------|-------------|--------|
|
||||
| TOP | Purple | noiseTOP, glslTOP, compositeTOP, levelTop, blurTOP, textTOP, nullTOP | TOP |
|
||||
| CHOP | Green | audiofileinCHOP, audiospectrumCHOP, mathCHOP, lfoCHOP, constantCHOP | CHOP |
|
||||
| SOP | Blue | gridSOP, sphereSOP, transformSOP, noiseSOP | SOP |
|
||||
| DAT | White | textDAT, tableDAT, scriptDAT, webserverDAT | DAT |
|
||||
| MAT | Yellow | phongMAT, pbrMAT, glslMAT, constMAT | MAT |
|
||||
| COMP | Gray | geometryCOMP, containerCOMP, cameraCOMP, lightCOMP, windowCOMP | COMP |
|
||||
|
||||
## Security Notes
|
||||
|
||||
- MCP runs on localhost only (port 40404). No authentication — any local process can send commands.
|
||||
- `td_execute_python` has unrestricted access to the TD Python environment and filesystem as the TD process user.
|
||||
- `setup.sh` downloads twozero.tox from the official 404zero.com URL. Verify the download if concerned.
|
||||
- The skill never sends data outside localhost. All MCP communication is local.
|
||||
|
||||
## References
|
||||
|
||||
| File | What |
|
||||
|------|------|
|
||||
| `references/pitfalls.md` | Hard-won lessons from real sessions |
|
||||
| `references/operators.md` | All operator families with params and use cases |
|
||||
| `references/network-patterns.md` | Recipes: audio-reactive, generative, GLSL, instancing |
|
||||
| `references/mcp-tools.md` | Full twozero MCP tool parameter schemas |
|
||||
| `references/python-api.md` | TD Python: op(), scripting, extensions |
|
||||
| `references/troubleshooting.md` | Connection diagnostics, debugging |
|
||||
| `references/glsl.md` | GLSL uniforms, built-in functions, shader templates |
|
||||
| `references/postfx.md` | Post-FX: bloom, CRT, chromatic aberration, feedback glow |
|
||||
| `references/layout-compositor.md` | HUD layout patterns, panel grids, BSP-style layouts |
|
||||
| `references/operator-tips.md` | Wireframe rendering, feedback TOP setup |
|
||||
| `references/geometry-comp.md` | Geometry COMP: instancing, POP vs SOP, morphing |
|
||||
| `references/audio-reactive.md` | Audio band extraction, beat detection, envelope following |
|
||||
| `references/animation.md` | LFOs, timers, keyframes, easing, expression-driven motion |
|
||||
| `references/midi-osc.md` | MIDI/OSC controllers, TouchOSC, multi-machine sync |
|
||||
| `references/particles.md` | POPs and legacy particleSOP — emission, forces, collisions |
|
||||
| `references/projection-mapping.md` | Multi-window output, corner pin, mesh warp, edge blending |
|
||||
| `references/external-data.md` | HTTP, WebSocket, MQTT, Serial, TCP, webserverDAT |
|
||||
| `references/panel-ui.md` | Custom params, panel COMPs, button/slider/field, panelExecuteDAT |
|
||||
| `references/replicator.md` | replicatorCOMP — data-driven cloning, layouts, callbacks |
|
||||
| `references/dat-scripting.md` | Execute DAT family — chop/dat/parameter/panel/op/executeDAT |
|
||||
| `references/3d-scene.md` | Lighting rigs, shadows, IBL/cubemaps, multi-camera, PBR |
|
||||
| `scripts/setup.sh` | Automated setup script |
|
||||
|
||||
---
|
||||
|
||||
> You're not writing code. You're conducting light.
|
||||
@@ -0,0 +1,269 @@
|
||||
---
|
||||
title: "Unreal Mcp — Automate Unreal Engine editor scenes, actors, and renders"
|
||||
sidebar_label: "Unreal Mcp"
|
||||
description: "Automate Unreal Engine editor scenes, actors, and renders"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Unreal Mcp
|
||||
|
||||
Automate Unreal Engine editor scenes, actors, and renders.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/creative/unreal-mcp` |
|
||||
| Path | `optional-skills/creative\unreal-mcp` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `unreal`, `unreal-engine`, `ue5`, `3d`, `mcp`, `scenes`, `cinematics`, `lighting`, `gamedev` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Unreal Engine MCP Skill
|
||||
|
||||
Companion skill for the `unreal-engine` entry in the Hermes MCP catalog. The
|
||||
MCP server (Epic's official, experimental "Unreal MCP" plugin, internal id
|
||||
`ModelContextProtocol`) runs INSIDE the Unreal Editor process and exposes
|
||||
editor functionality as typed tools. This skill teaches how to drive it well:
|
||||
discovering the live tool surface, sequencing calls safely, translating
|
||||
plain-English asks into scenes that actually look good, and verifying work
|
||||
visually. The user should never need to touch the editor beyond launching it.
|
||||
|
||||
## When to Use
|
||||
|
||||
Use when the user wants anything done in Unreal Engine: build or dress a
|
||||
level, spawn/move/delete actors, set up lighting and atmosphere, create or
|
||||
tune material instances, frame a camera shot, capture screenshots or renders,
|
||||
import assets, inspect the scene or UI, run automation tests, or script the
|
||||
editor. Works for single actions ("make the sun golden hour") and for
|
||||
complete multi-step projects ("build me a moody forest clearing with a
|
||||
campfire and render a shot of it").
|
||||
|
||||
Don't use for: DCC-style mesh modeling/sculpting (model in Blender and
|
||||
import the result), or for editing Unreal C++ project source (that's normal
|
||||
code work — use the terminal; this skill is about the live editor).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Two halves, in this order: the editor side must be up before Hermes connects.
|
||||
|
||||
### One-time, editor side
|
||||
|
||||
1. Unreal Editor **5.8+** with a project open. (macOS: full Xcode must be
|
||||
installed and its license accepted — the editor exits on first launch
|
||||
without it; see pitfalls.)
|
||||
2. **Edit > Plugins** — enable **Unreal MCP** (its Toolset Registry
|
||||
dependency auto-enables). Restart the editor when prompted.
|
||||
3. The typed toolsets ship separately from the server: also enable the
|
||||
**AllToolsets** plugin in the same Plugins browser. Unreal MCP ships NO
|
||||
tools itself — AllToolsets provides the shipped toolsets (SceneTools,
|
||||
ActorTools, MaterialInstanceTools, ObjectTools, …); skip it and the
|
||||
server connects but the agent has nothing to call.
|
||||
4. **Edit > Editor Preferences > General > Model Context Protocol** — enable
|
||||
**Auto Start Server**. Default bind is `http://127.0.0.1:8000/mcp`
|
||||
(port/path configurable in the same panel; server name is `unreal-mcp`).
|
||||
To start manually instead, run `ModelContextProtocol.StartServer` in the
|
||||
editor console (backtick key).
|
||||
|
||||
### One-time, Hermes side
|
||||
|
||||
hermes mcp install unreal-engine
|
||||
|
||||
This writes the `mcp_servers.unreal-engine` HTTP entry pointing at
|
||||
`http://127.0.0.1:8000/mcp` and probes the live server for its tools. Run it
|
||||
while the editor + server are up so the probe sees the real surface. If the
|
||||
user changed port/path in Editor Preferences, edit the `url` in
|
||||
`~/.hermes/config.yaml` under `mcp_servers.unreal-engine` to match.
|
||||
|
||||
Do NOT use `ModelContextProtocol.GenerateClientConfig` for Hermes — that
|
||||
writes `.mcp.json`-style files for Claude Code/Cursor/etc. Hermes connects
|
||||
from `config.yaml` via the catalog entry.
|
||||
|
||||
### Every session
|
||||
|
||||
1. Launch Unreal Editor, wait for the project to finish loading; confirm the
|
||||
server started (Output Log shows the bind address, or run
|
||||
`ModelContextProtocol.StartServer` manually).
|
||||
2. Start the Hermes session. Tools register as `mcp_unreal_engine_*`. If
|
||||
they're missing: editor wasn't up first — start it, then open a new
|
||||
Hermes session.
|
||||
3. Sanity check: call `mcp_unreal_engine_list_toolsets` and confirm toolsets
|
||||
come back.
|
||||
|
||||
## The Tool Surface: Discovery, Not a Fixed List
|
||||
|
||||
By default the plugin runs in **tool-search mode**: `tools/list` returns only
|
||||
three meta-tools, and every real tool is reached through them. Through Hermes
|
||||
they appear as:
|
||||
|
||||
| Hermes tool | Purpose |
|
||||
|---|---|
|
||||
| `mcp_unreal_engine_list_toolsets` | Names + descriptions of every registered toolset |
|
||||
| `mcp_unreal_engine_describe_toolset` | Full JSON schemas for one named toolset's tools |
|
||||
| `mcp_unreal_engine_call_tool` | Invoke a named tool with arguments, get the result |
|
||||
|
||||
The discovery walk, always in this order:
|
||||
|
||||
1. `list_toolsets` → see what capability groups this project actually has
|
||||
(the surface is project-dependent: enabled plugins, Game Feature Plugins,
|
||||
and any custom toolsets all contribute). Names come back FULLY QUALIFIED
|
||||
(`editor_toolset.toolsets.scene.SceneTools`,
|
||||
`EditorToolset.EditorAppToolset`) — use them verbatim as `toolset_name`.
|
||||
2. `describe_toolset` on the group you need → read the real parameter
|
||||
schemas. Never guess parameter names — schemas are the contract.
|
||||
3. `call_tool` with the qualified toolset name, the SHORT tool name
|
||||
(`find_actors`, not the dotted form), and arguments matching the schema.
|
||||
|
||||
Cache what you learn for the session; re-list only after the editor side
|
||||
changes (new plugin enabled, toolset authored, `RefreshTools` run).
|
||||
|
||||
The alternative eager mode (`Enable Tool Search` off in Editor Preferences)
|
||||
advertises every tool as its own `mcp_unreal_engine_<tool>` entry. Discovery
|
||||
then happens at `hermes mcp install`/`configure` time instead. Tool-search
|
||||
mode is the default and what this skill assumes; it also keeps schema tokens
|
||||
out of every API call, so prefer it.
|
||||
|
||||
See `references/tool-surface.md` for the shipped toolset catalog, authoring
|
||||
custom toolsets, and the full plugin configuration/console-command reference.
|
||||
|
||||
## Operating Loop
|
||||
|
||||
Every Unreal task follows the same loop:
|
||||
|
||||
1. **Inspect first.** List toolsets, then query the scene/level state before
|
||||
touching anything. Never assume an empty or default level. In an
|
||||
unfamiliar project, also check for project-registered Agent Skills
|
||||
(`call_tool` → `AgentSkillToolset.ListSkills`): a matching project skill's
|
||||
instructions override this skill's generic defaults.
|
||||
2. **Act in small, single-purpose calls.** One logical step per `call_tool`.
|
||||
The server executes tools **serially on the game thread** — a big
|
||||
monolithic operation freezes the editor UI until it finishes and risks
|
||||
client timeouts. Exception: for loops over 5+ homogeneous operations,
|
||||
ONE `ProgrammaticToolset.execute_tool_script` call batches them
|
||||
server-side without breaking the serial rule
|
||||
(`references/advanced-workflows.md`).
|
||||
3. **NEVER issue overlapping calls.** Do not batch multiple
|
||||
`mcp_unreal_engine_*` calls in one turn — Hermes runs batched calls
|
||||
concurrently, and parallel calls against the game thread deadlock or
|
||||
fail. Strictly one call, await result, next call. This overrides the
|
||||
general parallel-tool-calls guidance.
|
||||
4. **Read every result.** Many tools (Blueprint compiles, material edits,
|
||||
widget creation) report success/failure in the response body with no
|
||||
protocol-level exception. Anything that isn't an explicit success is a
|
||||
stop-and-diagnose, not a shrug. After property writes, read the value
|
||||
back — several write paths silently no-op (see pitfalls).
|
||||
5. **Verify visually and structurally.** After each milestone, confirm state
|
||||
by querying the actors/properties you changed, and capture a viewport
|
||||
screenshot when composition matters (see `references/tool-surface.md` for
|
||||
the capture options; `vision_analyze` the image — you are the art
|
||||
director, judge it).
|
||||
6. **Save often.** Editor edits are in-memory until packages/levels are
|
||||
saved; an editor crash loses everything since the last save, and MCP
|
||||
edits are not reliably undoable. Save before AND after any bulk change,
|
||||
and after every milestone.
|
||||
7. **Report concretely.** Actor labels, asset paths (`/Game/...`), file
|
||||
locations of captures/renders.
|
||||
|
||||
Rules of the world while you work:
|
||||
|
||||
- Units are **centimeters**; axes are **Z-up**, X-forward; rotations are
|
||||
degrees (Rotator: Roll around X, Pitch around Y, Yaw around Z). Human eye
|
||||
height ≈ 165 cm; a door ≈ 210×90 cm. Full tables in
|
||||
`references/scene-craft.md`.
|
||||
- Content paths use long package names: `/Game/Folder/Asset.Asset` for
|
||||
project content, `/Engine/BasicShapes/Cube.Cube` for engine primitives.
|
||||
- Actor **labels** (what you see in the Outliner, settable, non-unique) are
|
||||
not actor **names** (internal, unique). Prefer resolving actors by
|
||||
label/class queries, then hold on to whatever handle the tool returns.
|
||||
- Prefer physically-plausible lighting values (lux/candela/Kelvin) over
|
||||
arbitrary brightness numbers — but FIRST read the existing sun's
|
||||
intensity to learn the scene's calibration convention; template worlds
|
||||
are often calibrated around `intensity: 10`, and physical values blow
|
||||
them out (`references/scene-craft.md` has the numbers,
|
||||
`references/pitfalls.md` #12b has the calibration rule).
|
||||
|
||||
## From Plain English to a Scene
|
||||
|
||||
The user gives intent, not specs. Translate before you build:
|
||||
|
||||
1. **Extract the brief.** Subject, mood, time of day, interior/exterior,
|
||||
style, deliverable (screenshot? render? playable level?). Ask at most one
|
||||
round of clarifying questions, then commit — you are the technical
|
||||
director; don't bounce Unreal jargon back at the user.
|
||||
2. **Plan the build order.** The order that works: level/environment shell →
|
||||
blocking (major geometry/meshes in place) → lighting + atmosphere →
|
||||
materials → set dressing/detail → camera → capture/render. Post the plan
|
||||
as a todo list for multi-step builds.
|
||||
3. **Build with the loop above**, one milestone at a time, screenshot at
|
||||
each milestone.
|
||||
4. **Art-direct yourself.** Compare each screenshot against the brief:
|
||||
readable silhouette? believable light direction/intensity? horizon not
|
||||
dead-center? scale correct against a human-height reference? Fix before
|
||||
moving on.
|
||||
5. **Deliver.** Screenshots/renders as files (`MEDIA:` path), plus a short
|
||||
summary of what exists in the level and where it was saved.
|
||||
|
||||
`references/recipes.md` has complete worked builds (exterior daylight scene,
|
||||
moody interior, golden-hour cinematic + render, asset import & placement)
|
||||
with the exact call sequences and values.
|
||||
|
||||
## Reference Files
|
||||
|
||||
Load on demand; keep SKILL.md-level rules in mind throughout.
|
||||
|
||||
| Reference | Contents |
|
||||
|---|---|
|
||||
| `references/tool-surface.md` | Shipped toolsets catalog, discovery protocol detail, plugin console commands/CVars/flags, screenshot & capture paths, MCP Inspector debugging, extending with custom Python/C++ toolsets |
|
||||
| `references/advanced-workflows.md` | Sophisticated workflows, live-verified: ProgrammaticToolset batching, Blueprint DSL authoring loop (create→DSL→compile→spawn), PIE test sessions, Sequencer orientation (140 tools), LogsToolset self-debugging, automation testing, semantic asset search, config settings, per-situation decision table |
|
||||
| `references/scene-craft.md` | Numeric cheat sheet: physical light intensities, color temperatures, exposure/EV100, fog densities, mood recipes (noon/golden hour/overcast/night/interior), scale tables, content path conventions |
|
||||
| `references/recipes.md` | End-to-end worked builds with exact call sequences |
|
||||
| `references/pitfalls.md` | Setup, runtime, and workflow pitfalls with fixes — read before your first session and whenever something misbehaves |
|
||||
|
||||
## Pitfalls (top of mind — full list in references/pitfalls.md)
|
||||
|
||||
- **Start order matters.** Editor + server up first, then the Hermes
|
||||
session. Missing `mcp_unreal_engine_*` tools = wrong order.
|
||||
- **One call at a time.** Serial game thread; no batching, no overlap.
|
||||
- **The editor UI freezes during each call.** That's by design (game-thread
|
||||
execution). Warn the user during long operations; keep calls small.
|
||||
- **Modal dialogs block everything.** A tool call that opens (or collides
|
||||
with) a modal editor dialog stalls until a human dismisses it. If a call
|
||||
hangs indefinitely, tell the user to check the editor for a dialog.
|
||||
- **Timeouts on long operations.** Hermes' per-call default is 120 s; asset
|
||||
imports, big level saves, and renders can exceed it. Raise
|
||||
`mcp_servers.unreal-engine.timeout` in `~/.hermes/config.yaml` for
|
||||
render/import-heavy sessions.
|
||||
- **Stale tool schemas.** After authoring/hot-reloading toolsets or enabling
|
||||
a plugin, run `ModelContextProtocol.RefreshTools` in the editor console
|
||||
and re-`list_toolsets`. New C++ `UFUNCTION`s need a full editor restart —
|
||||
Live Coding won't surface them.
|
||||
- **Experimental plugin.** APIs and tool shapes can change between engine
|
||||
versions; trust `describe_toolset` over memory, including this skill's
|
||||
examples. When docs and the live schema disagree, the live schema wins.
|
||||
- **Don't expose the server beyond localhost.** Loopback-only, no auth, by
|
||||
design. Never suggest binding it wider.
|
||||
- **Licensing note.** The server logs on start: data transmitted via the
|
||||
plugin to a connected LLM service is Licensed Technology under the UE
|
||||
EULA (§6(e)) — the user is responsible for ensuring their LLM provider
|
||||
doesn't train on it. Surface this if the user asks about data handling.
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
- [ ] `list_toolsets` returns toolsets at session start (connection healthy)
|
||||
- [ ] Scene state queried before first edit (never assumed empty)
|
||||
- [ ] After each milestone: changed actors/properties re-queried and a
|
||||
screenshot reviewed against the brief
|
||||
- [ ] Level/dirty packages saved after each milestone and at the end
|
||||
- [ ] Deliverables exist on disk (screenshot/render paths confirmed) and are
|
||||
reported to the user with absolute paths
|
||||
- [ ] Editor left in a clean state: no pending modal, no unsaved surprise,
|
||||
user told exactly what was created/changed and where
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
---
|
||||
title: "Jupyter Notebook — Iterative Python via live Jupyter kernel (hamelnb)"
|
||||
sidebar_label: "Jupyter Notebook"
|
||||
description: "Iterative Python via live Jupyter kernel (hamelnb)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Jupyter Notebook
|
||||
|
||||
Iterative Python via live Jupyter kernel (hamelnb).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/data-science/jupyter-notebook` |
|
||||
| Path | `optional-skills/data-science\jupyter-notebook` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `jupyter`, `notebook`, `repl`, `data-science`, `exploration`, `iterative` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Jupyter Notebook (hamelnb live kernel)
|
||||
|
||||
Gives you a **stateful Python REPL** via a live Jupyter kernel. Variables persist
|
||||
across executions. Use this instead of `execute_code` when you need to build up
|
||||
state incrementally, explore APIs, inspect DataFrames, or iterate on complex code.
|
||||
|
||||
## When to Use This vs Other Tools
|
||||
|
||||
| Tool | Use When |
|
||||
|------|----------|
|
||||
| **This skill** | Iterative exploration, state across steps, data science, ML, "let me try this and check" |
|
||||
| `execute_code` | One-shot scripts needing hermes tool access (web_search, file ops). Stateless. |
|
||||
| `terminal` | Shell commands, builds, installs, git, process management |
|
||||
|
||||
**Rule of thumb:** If you'd want a Jupyter notebook for the task, use this skill.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **uv** must be installed (check: `which uv`)
|
||||
2. **JupyterLab** must be installed: `uv tool install jupyterlab`
|
||||
3. A Jupyter server must be running (see Setup below)
|
||||
|
||||
## Setup
|
||||
|
||||
The hamelnb script location:
|
||||
```
|
||||
SCRIPT="$HOME/.agent-skills/hamelnb/skills/jupyter-live-kernel/scripts/jupyter_live_kernel.py"
|
||||
```
|
||||
|
||||
If not cloned yet:
|
||||
```
|
||||
git clone https://github.com/hamelsmu/hamelnb.git ~/.agent-skills/hamelnb
|
||||
```
|
||||
|
||||
### Starting JupyterLab
|
||||
|
||||
Check if a server is already running:
|
||||
```
|
||||
uv run "$SCRIPT" servers
|
||||
```
|
||||
|
||||
If no servers found, start one:
|
||||
```
|
||||
jupyter-lab --no-browser --port=8888 --notebook-dir=$HOME/notebooks \
|
||||
--IdentityProvider.token='' --ServerApp.password='' > /tmp/jupyter.log 2>&1 &
|
||||
sleep 3
|
||||
```
|
||||
|
||||
Note: Token/password disabled for local agent access. The server runs headless.
|
||||
|
||||
### Creating a Notebook for REPL Use
|
||||
|
||||
If you just need a REPL (no existing notebook), create a minimal notebook file:
|
||||
```
|
||||
mkdir -p ~/notebooks
|
||||
```
|
||||
Write a minimal .ipynb JSON file with one empty code cell, then start a kernel
|
||||
session via the Jupyter REST API:
|
||||
```
|
||||
curl -s -X POST http://127.0.0.1:8888/api/sessions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"path":"scratch.ipynb","type":"notebook","name":"scratch.ipynb","kernel":{"name":"python"}}'
|
||||
```
|
||||
|
||||
## Core Workflow
|
||||
|
||||
All commands return structured JSON. Always use `--compact` to save tokens.
|
||||
|
||||
### 1. Discover servers and notebooks
|
||||
|
||||
```
|
||||
uv run "$SCRIPT" servers --compact
|
||||
uv run "$SCRIPT" notebooks --compact
|
||||
```
|
||||
|
||||
### 2. Execute code (primary operation)
|
||||
|
||||
```
|
||||
uv run "$SCRIPT" execute --path <notebook.ipynb> --code '<python code>' --compact
|
||||
```
|
||||
|
||||
State persists across execute calls. Variables, imports, objects all survive.
|
||||
|
||||
Multi-line code works with $'...' quoting:
|
||||
```
|
||||
uv run "$SCRIPT" execute --path scratch.ipynb --code $'import os\nfiles = os.listdir(".")\nprint(f"Found {len(files)} files")' --compact
|
||||
```
|
||||
|
||||
### 3. Inspect live variables
|
||||
|
||||
```
|
||||
uv run "$SCRIPT" variables --path <notebook.ipynb> list --compact
|
||||
uv run "$SCRIPT" variables --path <notebook.ipynb> preview --name <varname> --compact
|
||||
```
|
||||
|
||||
### 4. Edit notebook cells
|
||||
|
||||
```
|
||||
# View current cells
|
||||
uv run "$SCRIPT" contents --path <notebook.ipynb> --compact
|
||||
|
||||
# Insert a new cell
|
||||
uv run "$SCRIPT" edit --path <notebook.ipynb> insert \
|
||||
--at-index <N> --cell-type code --source '<code>' --compact
|
||||
|
||||
# Replace cell source (use cell-id from contents output)
|
||||
uv run "$SCRIPT" edit --path <notebook.ipynb> replace-source \
|
||||
--cell-id <id> --source '<new code>' --compact
|
||||
|
||||
# Delete a cell
|
||||
uv run "$SCRIPT" edit --path <notebook.ipynb> delete --cell-id <id> --compact
|
||||
```
|
||||
|
||||
### 5. Verification (restart + run all)
|
||||
|
||||
Only use when the user asks for a clean verification or you need to confirm
|
||||
the notebook runs top-to-bottom:
|
||||
|
||||
```
|
||||
uv run "$SCRIPT" restart-run-all --path <notebook.ipynb> --save-outputs --compact
|
||||
```
|
||||
|
||||
## Practical Tips from Experience
|
||||
|
||||
1. **First execution after server start may timeout** — the kernel needs a moment
|
||||
to initialize. If you get a timeout, just retry.
|
||||
|
||||
2. **The kernel Python is JupyterLab's Python** — packages must be installed in
|
||||
that environment. If you need additional packages, install them into the
|
||||
JupyterLab tool environment first.
|
||||
|
||||
3. **--compact flag saves significant tokens** — always use it. JSON output can
|
||||
be very verbose without it.
|
||||
|
||||
4. **For pure REPL use**, create a scratch.ipynb and don't bother with cell editing.
|
||||
Just use `execute` repeatedly.
|
||||
|
||||
5. **Argument order matters** — subcommand flags like `--path` go BEFORE the
|
||||
sub-subcommand. E.g.: `variables --path nb.ipynb list` not `variables list --path nb.ipynb`.
|
||||
|
||||
6. **If a session doesn't exist yet**, you need to start one via the REST API
|
||||
(see Setup section). The tool can't execute without a live kernel session.
|
||||
|
||||
7. **Errors are returned as JSON** with traceback — read the `ename` and `evalue`
|
||||
fields to understand what went wrong.
|
||||
|
||||
8. **Occasional websocket timeouts** — some operations may timeout on first try,
|
||||
especially after a kernel restart. Retry once before escalating.
|
||||
|
||||
9. **If websocket consistently times out on this host**, force zmq transport:
|
||||
`uv run "$SCRIPT" execute --transport zmq ...`. Symptom: every execute returns
|
||||
"Websocket execution may already have reached the kernel, so auto fallback was
|
||||
skipped". The kernel actually ran fine (REST shows execution_state=idle and
|
||||
execution_count increments) — only the websocket reply channel is broken.
|
||||
zmq transport uses jupyter_client directly and sidesteps the issue.
|
||||
|
||||
10. **When starting a fresh server for REST-only use**, add
|
||||
`--ServerApp.disable_check_xsrf=True` — otherwise POST /api/sessions returns
|
||||
`"'_xsrf' argument missing from POST"` and kernel session creation fails.
|
||||
|
||||
## Timeout Defaults
|
||||
|
||||
The script has a 30-second default timeout per execution. For long-running
|
||||
operations, pass `--timeout 120`. Use generous timeouts (60+) for initial
|
||||
setup or heavy computation.
|
||||
@@ -0,0 +1,164 @@
|
||||
---
|
||||
title: "Actual Setup — Set up Actual Computer (actual.inc) inference in Hermes"
|
||||
sidebar_label: "Actual Setup"
|
||||
description: "Set up Actual Computer (actual.inc) inference in Hermes"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Actual Setup
|
||||
|
||||
Set up Actual Computer (actual.inc) inference in Hermes.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/devops/actual-setup` |
|
||||
| Path | `optional-skills/devops\actual-setup` |
|
||||
| Version | `2.0.0` |
|
||||
| Author | shl0ms + Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `actual`, `actual-inc`, `provider`, `local-inference`, `relay`, `gguf`, `setup` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Actual Computer Setup Skill
|
||||
|
||||
Sets up [actual.inc](https://actual.inc) (Actual Computer) as a Hermes inference
|
||||
provider. Actual turns the user's own hardware into a private inference cluster
|
||||
and exposes an OpenAI-compatible API two ways: a hosted end-to-end-encrypted
|
||||
relay at `https://api.actual.inc` (authenticated with an `ac_` key), and a local
|
||||
on-device daemon at `http://127.0.0.1:8080` (no auth on loopback). This skill
|
||||
does not install the Actual daemon for the user — device authorization requires
|
||||
a human in a browser.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User wants to add actual.inc as an inference provider (cloud relay or local).
|
||||
- User has an `ac_` key and wants Hermes routed through their Actual cluster.
|
||||
- User wants fully-local, on-device inference via the Actual daemon.
|
||||
- Troubleshooting: Actual requests failing with cryptic 400s or empty streams.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Hermes has **first-class `actual` provider support** (provider id `actual`,
|
||||
aliases `actual-computer`, `actualcomputer`, `aci`). Do NOT configure Actual
|
||||
as a `custom_providers` / `providers.actual.*` entry on current Hermes — the
|
||||
built-in provider owns the name and handles base-url normalization, the
|
||||
Responses transport, and local no-auth automatically.
|
||||
- Relay mode: an Actual account and an `ac_` inference key from
|
||||
https://actual.inc/user/keys.
|
||||
- Local mode: the user has installed the daemon
|
||||
(`curl -fsSL "https://actual.inc/install" | bash`) and completed device
|
||||
authorization by running `actual` once and opening the printed
|
||||
`https://actual.inc/device?code=...` URL in a browser. Relay that URL to the
|
||||
user and WAIT — never invent an email or authorize on their behalf. Codes
|
||||
expire in 5 minutes; re-run `actual` for a fresh one.
|
||||
|
||||
## How to Run
|
||||
|
||||
### Relay / API mode
|
||||
|
||||
1. Put the key in `.env` (secrets only — never config.yaml):
|
||||
append `ACTUAL_API_KEY=ac_...` to `~/.hermes/.env`.
|
||||
2. Verify the key and discover models with `terminal`:
|
||||
```bash
|
||||
curl -s https://api.actual.inc/v1/models -H "Authorization: Bearer $ACTUAL_API_KEY"
|
||||
```
|
||||
3. Select provider + model:
|
||||
```bash
|
||||
hermes config set model.provider actual
|
||||
hermes config set model.default "MODEL_ID_FROM_DISCOVERY"
|
||||
```
|
||||
4. Verify end-to-end:
|
||||
```bash
|
||||
hermes chat -Q -q "Reply with exactly: ACTUAL_OK" --provider actual -m MODEL_ID
|
||||
```
|
||||
|
||||
### Local mode
|
||||
|
||||
1. Human has installed + authorized the daemon (see Prerequisites).
|
||||
2. Download and load a model (scriptable once authorized):
|
||||
```bash
|
||||
actual models search "qwen2.5 0.5b instruct gguf" --limit 8 --no-prompt
|
||||
# Downloads REQUIRE an explicit quantization (409 ambiguous_model_download otherwise):
|
||||
actual models download "Qwen/Qwen2.5-0.5B-Instruct-GGUF/Q4_K_M"
|
||||
actual models list # note the INSTALLED name (differs from download id)
|
||||
actual models load "qwen2.5-0.5b-instruct-q4_k_m" # load by installed name
|
||||
```
|
||||
3. Point Hermes at the daemon. `ACTUAL_BASE_URL` with a loopback host flips the
|
||||
built-in provider into local no-auth mode automatically — no key needed:
|
||||
append `ACTUAL_BASE_URL=http://127.0.0.1:8080` to `~/.hermes/.env`, then:
|
||||
```bash
|
||||
hermes config set model.provider actual
|
||||
hermes config set model.default "INSTALLED_MODEL_NAME"
|
||||
```
|
||||
4. Verify (reduced toolset — see context-window pitfall below):
|
||||
```bash
|
||||
hermes chat -Q -q "Reply with exactly: LOCAL_OK" --provider actual -m INSTALLED_NAME -t file,web
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Thing | Value |
|
||||
|---|---|
|
||||
| Hosted relay | `https://api.actual.inc/v1` (normalized from bare host automatically) |
|
||||
| Local daemon | `http://127.0.0.1:8080/v1` (no auth on loopback) |
|
||||
| Key env var | `ACTUAL_API_KEY` (`ac_...`) |
|
||||
| Base URL env var | `ACTUAL_BASE_URL` (loopback host ⇒ local no-auth mode) |
|
||||
| Provider id / aliases | `actual` / `actual-computer`, `actualcomputer`, `aci` |
|
||||
| Transport | Responses API (`codex_responses`) — built-in, do not override |
|
||||
| Cluster pinning | `X-Cluster-ID` header via `providers.actual.extra_headers` in config.yaml |
|
||||
| Model size guide | 0.5B Q4_K_M ~470MB (toy), 7-8B Q4_K_M ~4.5GB (daily driver), 32B ~20GB |
|
||||
|
||||
## Pitfalls
|
||||
|
||||
1. **reasoning_effort trap (handled by Hermes since the first-class provider).**
|
||||
Actual's SGLang/vLLM backends accept only `none/low/medium/high/max`;
|
||||
`xhigh`/`ultra` used to fail with a cryptic
|
||||
`Expecting value: line 1 column 1 (char 0)` (a wrapped HTTP 400). The
|
||||
built-in provider clamps `xhigh→high` and `ultra→max` on the wire. If a
|
||||
request still 400s this way on an old Hermes, set a per-model cap:
|
||||
`agent.reasoning_overrides.<model>: high` in config.yaml.
|
||||
2. **Context-window overflow on small local models.** Hermes' default toolset
|
||||
is ~26k tokens of schemas plus a ~9k-token system prompt. A model loaded
|
||||
with a 32k context overflows before the first turn, and llama.cpp-family
|
||||
servers emit a bare `data: [DONE]` — Hermes reports
|
||||
`Provider returned an empty stream with no finish_reason`. This is NOT an
|
||||
SSE bug. Fixes: restrict tools (`-t file,web`), load the model with a
|
||||
larger `n_ctx`, or pick a >=64k-context model for the full toolset.
|
||||
Upstream tracking: #51448 (do not file new issues; add evidence there).
|
||||
Related but distinct: #65631 (HTTP-200 SSE carrying a 400), #56516
|
||||
(reasoning-only streams).
|
||||
3. **Download ids vs installed names.** `actual models download` takes
|
||||
`repo/QUANT` and 409s without an explicit quantization;
|
||||
`actual models load` takes the INSTALLED name from `actual models list`.
|
||||
4. **Reasoning models returning empty content.** GLM/Qwen reasoning variants
|
||||
emit thinking in a separate `reasoning` field and can burn a small
|
||||
`max_tokens` entirely on reasoning. Give generous max_tokens before
|
||||
assuming failure.
|
||||
5. **Do not create a custom provider named `actual`.** Older setup guides
|
||||
(pre first-class support) wrote `providers.actual.*` config blocks. On
|
||||
current Hermes the built-in provider wins the name; stale custom blocks
|
||||
are ignored or conflict. Remove them and use the env vars + model.provider
|
||||
flow above.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
# Relay:
|
||||
hermes chat -Q -q "Reply with exactly: ACTUAL_OK" --provider actual -m MODEL
|
||||
# Local (small model — reduced toolset):
|
||||
hermes chat -Q -q "Reply with exactly: LOCAL_OK" --provider actual -m MODEL -t file,web
|
||||
# Provider status (local no-auth shows key_source=local-offline):
|
||||
hermes status
|
||||
```
|
||||
|
||||
For other OpenAI-compatible clients (e.g. OpenCode), see
|
||||
`references/opencode.md`.
|
||||
@@ -0,0 +1,298 @@
|
||||
---
|
||||
title: "Docker Management — Manage Docker containers, images, volumes, and Compose"
|
||||
sidebar_label: "Docker Management"
|
||||
description: "Manage Docker containers, images, volumes, and Compose"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Docker Management
|
||||
|
||||
Manage Docker containers, images, volumes, and Compose.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/devops/docker-management` |
|
||||
| Path | `optional-skills/devops\docker-management` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | sprmn24 |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `docker`, `containers`, `devops`, `infrastructure`, `compose`, `images`, `volumes`, `networks`, `debugging` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Docker Management
|
||||
|
||||
Manage Docker containers, images, volumes, networks, and Compose stacks using standard Docker CLI commands. No additional dependencies beyond Docker itself.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Run, stop, restart, remove, or inspect containers
|
||||
- Build, pull, push, tag, or clean up Docker images
|
||||
- Work with Docker Compose (multi-service stacks)
|
||||
- Manage volumes or networks
|
||||
- Debug a crashing container or analyze logs
|
||||
- Check Docker disk usage or free up space
|
||||
- Review or optimize a Dockerfile
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker Engine installed and running
|
||||
- User added to the `docker` group (or use `sudo`)
|
||||
- Docker Compose v2 (included with modern Docker installations)
|
||||
|
||||
Quick check:
|
||||
|
||||
```bash
|
||||
docker --version && docker compose version
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Task | Command |
|
||||
|------|---------|
|
||||
| Run container (background) | `docker run -d --name NAME IMAGE` |
|
||||
| Stop + remove | `docker stop NAME && docker rm NAME` |
|
||||
| View logs (follow) | `docker logs --tail 50 -f NAME` |
|
||||
| Shell into container | `docker exec -it NAME /bin/sh` |
|
||||
| List all containers | `docker ps -a` |
|
||||
| Build image | `docker build -t TAG .` |
|
||||
| Compose up | `docker compose up -d` |
|
||||
| Compose down | `docker compose down` |
|
||||
| Disk usage | `docker system df` |
|
||||
| Cleanup dangling | `docker image prune && docker container prune` |
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Identify the domain
|
||||
|
||||
Figure out which area the request falls into:
|
||||
|
||||
- **Container lifecycle** → run, stop, start, restart, rm, pause/unpause
|
||||
- **Container interaction** → exec, cp, logs, inspect, stats
|
||||
- **Image management** → build, pull, push, tag, rmi, save/load
|
||||
- **Docker Compose** → up, down, ps, logs, exec, build, config
|
||||
- **Volumes & networks** → create, inspect, rm, prune, connect
|
||||
- **Troubleshooting** → log analysis, exit codes, resource issues
|
||||
|
||||
### 2. Container operations
|
||||
|
||||
**Run a new container:**
|
||||
|
||||
```bash
|
||||
# Detached service with port mapping
|
||||
docker run -d --name web -p 8080:80 nginx
|
||||
|
||||
# With environment variables
|
||||
docker run -d -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=mydb --name db postgres:16
|
||||
|
||||
# With persistent data (named volume)
|
||||
docker run -d -v pgdata:/var/lib/postgresql/data --name db postgres:16
|
||||
|
||||
# For development (bind mount source code)
|
||||
docker run -d -v $(pwd)/src:/app/src -p 3000:3000 --name dev my-app
|
||||
|
||||
# Interactive debugging (auto-remove on exit)
|
||||
docker run -it --rm ubuntu:22.04 /bin/bash
|
||||
|
||||
# With resource limits and restart policy
|
||||
docker run -d --memory=512m --cpus=1.5 --restart=unless-stopped --name app my-app
|
||||
```
|
||||
|
||||
Key flags: `-d` detached, `-it` interactive+tty, `--rm` auto-remove, `-p` port (host:container), `-e` env var, `-v` volume, `--name` name, `--restart` restart policy.
|
||||
|
||||
**Manage running containers:**
|
||||
|
||||
```bash
|
||||
docker ps # running containers
|
||||
docker ps -a # all (including stopped)
|
||||
docker stop NAME # graceful stop
|
||||
docker start NAME # start stopped container
|
||||
docker restart NAME # stop + start
|
||||
docker rm NAME # remove stopped container
|
||||
docker rm -f NAME # force remove running container
|
||||
docker container prune # remove ALL stopped containers
|
||||
```
|
||||
|
||||
**Interact with containers:**
|
||||
|
||||
```bash
|
||||
docker exec -it NAME /bin/sh # shell access (use /bin/bash if available)
|
||||
docker exec NAME env # view environment variables
|
||||
docker exec -u root NAME apt update # run as specific user
|
||||
docker logs --tail 100 -f NAME # follow last 100 lines
|
||||
docker logs --since 2h NAME # logs from last 2 hours
|
||||
docker cp NAME:/path/file ./local # copy file from container
|
||||
docker cp ./file NAME:/path/ # copy file to container
|
||||
docker inspect NAME # full container details (JSON)
|
||||
docker stats --no-stream # resource usage snapshot
|
||||
docker top NAME # running processes
|
||||
```
|
||||
|
||||
### 3. Image management
|
||||
|
||||
```bash
|
||||
# Build
|
||||
docker build -t my-app:latest .
|
||||
docker build -t my-app:prod -f Dockerfile.prod .
|
||||
docker build --no-cache -t my-app . # clean rebuild
|
||||
DOCKER_BUILDKIT=1 docker build -t my-app . # faster with BuildKit
|
||||
|
||||
# Pull and push
|
||||
docker pull node:20-alpine
|
||||
docker login ghcr.io
|
||||
docker tag my-app:latest registry/my-app:v1.0
|
||||
docker push registry/my-app:v1.0
|
||||
|
||||
# Inspect
|
||||
docker images # list local images
|
||||
docker history IMAGE # see layers
|
||||
docker inspect IMAGE # full details
|
||||
|
||||
# Cleanup
|
||||
docker image prune # remove dangling (untagged) images
|
||||
docker image prune -a # remove ALL unused images (careful!)
|
||||
docker image prune -a --filter "until=168h" # unused images older than 7 days
|
||||
```
|
||||
|
||||
### 4. Docker Compose
|
||||
|
||||
```bash
|
||||
# Start/stop
|
||||
docker compose up -d # start all services detached
|
||||
docker compose up -d --build # rebuild images before starting
|
||||
docker compose down # stop and remove containers
|
||||
docker compose down -v # also remove volumes (DESTROYS DATA)
|
||||
|
||||
# Monitoring
|
||||
docker compose ps # list services
|
||||
docker compose logs -f api # follow logs for specific service
|
||||
docker compose logs --tail 50 # last 50 lines all services
|
||||
|
||||
# Interaction
|
||||
docker compose exec api /bin/sh # shell into running service
|
||||
docker compose run --rm api npm test # one-off command (new container)
|
||||
docker compose restart api # restart specific service
|
||||
|
||||
# Validation
|
||||
docker compose config # validate and view resolved config
|
||||
```
|
||||
|
||||
**Minimal compose.yml example:**
|
||||
|
||||
```yaml
|
||||
services:
|
||||
api:
|
||||
build: .
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
# Password comes from the POSTGRES_PASSWORD secret, not the URL
|
||||
- DATABASE_URL=postgres://mydb_user@db:5432/mydb
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_USER: user
|
||||
POSTGRES_PASSWORD: pass
|
||||
POSTGRES_DB: mydb
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U user"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
```
|
||||
|
||||
### 5. Volumes and networks
|
||||
|
||||
```bash
|
||||
# Volumes
|
||||
docker volume ls # list volumes
|
||||
docker volume create mydata # create named volume
|
||||
docker volume inspect mydata # details (mount point, etc.)
|
||||
docker volume rm mydata # remove (fails if in use)
|
||||
docker volume prune # remove unused volumes
|
||||
|
||||
# Networks
|
||||
docker network ls # list networks
|
||||
docker network create mynet # create bridge network
|
||||
docker network inspect mynet # details (connected containers)
|
||||
docker network connect mynet NAME # attach container to network
|
||||
docker network disconnect mynet NAME # detach container
|
||||
docker network rm mynet # remove network
|
||||
docker network prune # remove unused networks
|
||||
```
|
||||
|
||||
### 6. Disk usage and cleanup
|
||||
|
||||
Always start with a diagnostic before cleaning:
|
||||
|
||||
```bash
|
||||
# Check what's using space
|
||||
docker system df # summary
|
||||
docker system df -v # detailed breakdown
|
||||
|
||||
# Targeted cleanup (safe)
|
||||
docker container prune # stopped containers
|
||||
docker image prune # dangling images
|
||||
docker volume prune # unused volumes
|
||||
docker network prune # unused networks
|
||||
|
||||
# Aggressive cleanup (confirm with user first!)
|
||||
docker system prune # containers + images + networks
|
||||
docker system prune -a # also unused images
|
||||
docker system prune -a --volumes # EVERYTHING — named volumes too
|
||||
```
|
||||
|
||||
**Warning:** Never run `docker system prune -a --volumes` without confirming with the user. This removes named volumes with potentially important data.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
| Problem | Cause | Fix |
|
||||
|---------|-------|-----|
|
||||
| Container exits immediately | Main process finished or crashed | Check `docker logs NAME`, try `docker run -it --entrypoint /bin/sh IMAGE` |
|
||||
| "port is already allocated" | Another process using that port | `docker ps` or `lsof -i :PORT` to find it |
|
||||
| "no space left on device" | Docker disk full | `docker system df` then targeted prune |
|
||||
| Can't connect to container | App binds to 127.0.0.1 inside container | App must bind to `0.0.0.0`, check `-p` mapping |
|
||||
| Permission denied on volume | UID/GID mismatch host vs container | Use `--user $(id -u):$(id -g)` or fix permissions |
|
||||
| Compose services can't reach each other | Wrong network or service name | Services use service name as hostname, check `docker compose config` |
|
||||
| Build cache not working | Layer order wrong in Dockerfile | Put rarely-changing layers first (deps before source code) |
|
||||
| Image too large | No multi-stage build, no .dockerignore | Use multi-stage builds, add `.dockerignore` |
|
||||
|
||||
## Verification
|
||||
|
||||
After any Docker operation, verify the result:
|
||||
|
||||
- **Container started?** → `docker ps` (check status is "Up")
|
||||
- **Logs clean?** → `docker logs --tail 20 NAME` (no errors)
|
||||
- **Port accessible?** → `curl -s http://localhost:PORT` or `docker port NAME`
|
||||
- **Image built?** → `docker images | grep TAG`
|
||||
- **Compose stack healthy?** → `docker compose ps` (all services "running" or "healthy")
|
||||
- **Disk freed?** → `docker system df` (compare before/after)
|
||||
|
||||
## Dockerfile Optimization Tips
|
||||
|
||||
When reviewing or creating a Dockerfile, suggest these improvements:
|
||||
|
||||
1. **Multi-stage builds** — separate build environment from runtime to reduce final image size
|
||||
2. **Layer ordering** — put dependencies before source code so changes don't invalidate cached layers
|
||||
3. **Combine RUN commands** — fewer layers, smaller image
|
||||
4. **Use .dockerignore** — exclude `node_modules`, `.git`, `__pycache__`, etc.
|
||||
5. **Pin base image versions** — `node:20-alpine` not `node:latest`
|
||||
6. **Run as non-root** — add `USER` instruction for security
|
||||
7. **Use slim/alpine bases** — `python:3.12-slim` not `python:3.12`
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
---
|
||||
title: "Hermes S6 Container Supervision — Modify or debug s6 services in the Hermes Docker image"
|
||||
sidebar_label: "Hermes S6 Container Supervision"
|
||||
description: "Modify or debug s6 services in the Hermes Docker image"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Hermes S6 Container Supervision
|
||||
|
||||
Modify or debug s6 services in the Hermes Docker image.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/devops/hermes-s6-container-supervision` |
|
||||
| Path | `optional-skills/devops\hermes-s6-container-supervision` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux |
|
||||
| Tags | `docker`, `s6`, `supervision`, `gateway`, `profiles` |
|
||||
| Related skills | [`hermes-agent`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Hermes s6-overlay Container Supervision
|
||||
|
||||
## When to use this skill
|
||||
|
||||
Load this skill when you're working on:
|
||||
- Adding or removing a static service in the Hermes Docker image (something that should be supervised at every container start, like the dashboard)
|
||||
- Diagnosing why a per-profile gateway isn't starting, restarting, or surviving `docker restart`
|
||||
- Understanding why the container's CMD is `/opt/hermes/docker/main-wrapper.sh` and how leading-dash args reach the user's program
|
||||
- Modifying `cont-init.d` boot scripts (UID remap, volume seeding, profile reconciliation)
|
||||
- Changing the rendered run-script for per-profile gateways (Phase 4)
|
||||
|
||||
If you're just running the Hermes Agent and want to use Docker, see `website/docs/user-guide/docker.md` instead.
|
||||
|
||||
## Architecture at a glance
|
||||
|
||||
<!-- ascii-guard-ignore -->
|
||||
```
|
||||
/init ← PID 1 (s6-overlay v3.2.3.0)
|
||||
├── cont-init.d ← oneshot setup, runs as root
|
||||
│ ├── 01-hermes-setup ← docker/stage2-hook.sh
|
||||
│ │ ├── UID/GID remap
|
||||
│ │ ├── chown /opt/data
|
||||
│ │ ├── chown /opt/data/profiles (every boot)
|
||||
│ │ ├── seed .env / config.yaml / SOUL.md
|
||||
│ │ └── skills_sync.py
|
||||
│ └── 02-reconcile-profiles ← hermes_cli.container_boot
|
||||
│ ├── chown /run/service (hermes-writable for runtime register)
|
||||
│ └── walk $HERMES_HOME/profiles/<name>/gateway_state.json
|
||||
│ → recreate /run/service/gateway-<name>/
|
||||
│ → auto-start only those with prior_state == "running"
|
||||
│
|
||||
├── s6-rc.d (static services, in /etc/s6-overlay/s6-rc.d/)
|
||||
│ ├── main-hermes/run ← exec sleep infinity (no-op slot)
|
||||
│ └── dashboard/run ← if HERMES_DASHBOARD=1, runs `hermes dashboard`
|
||||
│
|
||||
├── /run/service (s6-svscan watches; tmpfs)
|
||||
│ ├── gateway-coder/ ← runtime-registered per-profile
|
||||
│ │ ├── type ("longrun")
|
||||
│ │ ├── run ("#!/command/with-contenv sh ... exec s6-setuidgid hermes hermes -p coder gateway run")
|
||||
│ │ ├── down (marker — present means "registered but don't auto-start")
|
||||
│ │ └── log/run (s6-log → $HERMES_HOME/logs/gateways/coder/current)
|
||||
│ └── ...
|
||||
│
|
||||
└── CMD ("main program") ← /opt/hermes/docker/main-wrapper.sh
|
||||
└── routes user args: bare exec | hermes subcommand | hermes (no args)
|
||||
— exec'd by /init with stdin/stdout/stderr inherited (TTY for --tui)
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
## Key files
|
||||
|
||||
| Path | Role |
|
||||
|---|---|
|
||||
| `Dockerfile` | s6-overlay install + cont-init.d wiring + `ENTRYPOINT ["/opt/hermes/docker/entrypoint-dispatch.sh"]` |
|
||||
| `docker/entrypoint-dispatch.sh` | PID-1 dispatcher: exec's `/init` + main-wrapper when the image owns PID 1; on wrapped runtimes (Fly Machines, `docker run --init`) falls back to stage2-hook + main-wrapper directly, restoring the s6 helper PATH first (#38349). |
|
||||
| `docker/stage2-hook.sh` | The "old entrypoint logic" — UID remap, chown, seed, skills sync. Runs as cont-init.d/01-hermes-setup. |
|
||||
| `docker/cont-init.d/02-reconcile-profiles` | Calls `hermes_cli.container_boot` on every boot to restore profile gateway slots from the persistent volume. |
|
||||
| `docker/main-wrapper.sh` | The container's CMD. Routes user args, drops to hermes via `s6-setuidgid`, exec's the chosen program. |
|
||||
| `docker/s6-rc.d/main-hermes/run` | No-op `sleep infinity` — slot exists so the s6-rc user bundle is valid; main hermes runs as the CMD, not as a supervised service. |
|
||||
| `docker/s6-rc.d/dashboard/run` | Conditional service — `exec sleep infinity` unless `HERMES_DASHBOARD` is truthy. |
|
||||
| `docker/entrypoint.sh` | Back-compat shim that `exec`s the stage2 hook. External scripts that hard-coded the old entrypoint path still work. |
|
||||
| `hermes_cli/service_manager.py` | `S6ServiceManager`: `register_profile_gateway`, `unregister_profile_gateway`, `start/stop/restart/is_running`, `list_profile_gateways`. |
|
||||
| `hermes_cli/container_boot.py` | `reconcile_profile_gateways()` — walks persistent profiles, regenerates s6 slots, emits `container-boot.log`. |
|
||||
| `hermes_cli/gateway.py::_dispatch_via_service_manager_if_s6` | Intercepts `hermes gateway start/stop/restart` and routes to s6 when running in a container. |
|
||||
|
||||
## Why Architecture B (CMD as main program, not s6-supervised)
|
||||
|
||||
The original plan (v1–v3) called for main hermes to run as a supervised s6-rc service. Two real s6-overlay v3 mechanics blocked that:
|
||||
|
||||
1. **cont-init.d scripts receive no CMD args** — so the stage2 hook can't parse `docker run <image> chat -q "hi"` to set `HERMES_ARGS` for a service `run` script to consume.
|
||||
2. **`/run/s6/basedir/bin/halt` does NOT propagate the exit code** written to `/run/s6-linux-init-container-results/exitcode`. Containers always exit 143 (SIGTERM) regardless. Confirmed by skarnet (s6 author) in [issue #477](https://github.com/just-containers/s6-overlay/issues/477): _"if you want a container shutdown, you need to either have your CMD exit, or, if you have no CMD, write the container exit code you want then call halt"_.
|
||||
|
||||
So we use the s6-overlay-native CMD pattern via the dispatcher: `ENTRYPOINT ["/opt/hermes/docker/entrypoint-dispatch.sh"]`, which under PID 1 exec's `/init /opt/hermes/docker/main-wrapper.sh "$@"`. The wrapper is prepended to user args automatically — so `docker run <image> --version` becomes `/init main-wrapper.sh --version`, and `--version` doesn't get intercepted by /init's POSIX shell. The wrapper drops to hermes via `s6-setuidgid`, then exec's the chosen program. The program's exit code becomes the container exit code, exactly matching the pre-s6 tini contract. When the entrypoint is NOT PID 1 (Fly Machines, `docker run --init`), the dispatcher skips `/init` entirely (it would abort with `can only run as pid 1`), restores the s6 helper PATH, runs stage2-hook.sh, and exec's main-wrapper.sh directly — no supervised services on that path (#38349).
|
||||
|
||||
Trade-off: main hermes is unsupervised under s6. That exactly matches its behavior under tini (the pre-s6 image). Dashboard supervision is the only **new** guarantee — and per-profile gateways under `/run/service/` get full supervision.
|
||||
|
||||
## Quick recipes
|
||||
|
||||
### Verify s6 is PID 1 in a running container
|
||||
|
||||
```sh
|
||||
docker exec <c> sh -c 'cat /proc/1/comm; readlink /proc/1/exe'
|
||||
# Expect: s6-svscan or init / /package/admin/s6/.../s6-svscan
|
||||
```
|
||||
|
||||
### Inspect a profile gateway service
|
||||
|
||||
```sh
|
||||
# /command/ isn't on docker-exec PATH — use absolute path
|
||||
docker exec <c> /command/s6-svstat /run/service/gateway-<name>
|
||||
# "up (pid …) … seconds" → running
|
||||
# "down (exitcode N) … seconds, normally up, want up, …" → s6 wants it up but the process keeps exiting (crash loop)
|
||||
# "down … normally up, ready …" → user stopped it
|
||||
```
|
||||
|
||||
### Bring a service up/down manually
|
||||
|
||||
```sh
|
||||
docker exec <c> /command/s6-svc -u /run/service/gateway-<name> # up
|
||||
docker exec <c> /command/s6-svc -d /run/service/gateway-<name> # down
|
||||
docker exec <c> /command/s6-svc -t /run/service/gateway-<name> # SIGTERM (restart)
|
||||
```
|
||||
|
||||
### Watch the cont-init reconciler log
|
||||
|
||||
```sh
|
||||
docker exec <c> tail -n 50 /opt/data/logs/container-boot.log
|
||||
# 2026-05-21T06:18:05+0000 profile=coder prior_state=running action=started
|
||||
# 2026-05-21T06:18:05+0000 profile=writer prior_state=stopped action=registered
|
||||
```
|
||||
|
||||
### Add a new static service
|
||||
|
||||
1. Create `docker/s6-rc.d/<name>/type` with `longrun\n` and `docker/s6-rc.d/<name>/run` (use `#!/command/with-contenv sh` + `# shellcheck shell=sh`).
|
||||
2. Drop to hermes via `s6-setuidgid hermes` at the top of run (unless you specifically need root).
|
||||
3. Create empty `docker/s6-rc.d/<name>/dependencies.d/base` so it waits for the base bundle.
|
||||
4. Create empty `docker/s6-rc.d/user/contents.d/<name>` so it joins the user bundle.
|
||||
5. The `COPY docker/s6-rc.d/` in the Dockerfile picks it up automatically — no other changes.
|
||||
|
||||
### Change the per-profile gateway run command
|
||||
|
||||
Edit `S6ServiceManager._render_run_script` in `hermes_cli/service_manager.py`. The function is also called by `hermes_cli/container_boot.py::_register_service` during boot reconciliation, so it's the single source of truth. Update the corresponding assertion in `tests/hermes_cli/test_service_manager.py::test_s6_register_creates_service_dir_and_triggers_scan`.
|
||||
|
||||
### Run the docker test harness
|
||||
|
||||
```sh
|
||||
docker build -t hermes-agent-harness:latest .
|
||||
HERMES_TEST_IMAGE=hermes-agent-harness:latest scripts/run_tests.sh tests/docker/ -v
|
||||
# Expect 19 passed, 0 xfailed against the s6 image
|
||||
```
|
||||
|
||||
The harness lives in `tests/docker/` and skips when Docker isn't available. The per-test timeout is bumped to 180s (see `tests/docker/conftest.py`).
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
### "command not found" via `docker exec`
|
||||
|
||||
`/command/` (where s6-overlay puts its binaries) is on PATH only for processes spawned by the supervision tree — services, cont-init.d, main-wrapper.sh. `docker exec <c> s6-svstat …` will fail with "command not found"; always use the absolute path `/command/s6-svstat`. The `hermes` binary works because the Dockerfile adds `/opt/hermes/.venv/bin` to the runtime `ENV PATH`.
|
||||
|
||||
### Profile directory ownership
|
||||
|
||||
The cont-init reconciler runs as hermes (`s6-setuidgid hermes` in `02-reconcile-profiles`). If a profile dir ends up root-owned (e.g. because `docker exec <c> hermes profile create …` ran as root by default), the reconciler can't read SOUL.md and fails with `PermissionError`. Mitigation: `stage2-hook.sh` chowns `$HERMES_HOME/profiles` to hermes on **every** boot, idempotently. Don't remove that block.
|
||||
|
||||
### Files written by `docker exec` are root-owned
|
||||
|
||||
`docker exec` defaults to root. Either pass `--user hermes` or rely on the stage2 chown sweep next reboot. Don't write files under `$HERMES_HOME/profiles/<name>/` as root manually — the next reconcile pass will sweep them but in-flight operations may hit perm errors.
|
||||
|
||||
### Service slot exists but s6-svstat says "s6-supervise not running"
|
||||
|
||||
The service directory is on tmpfs and was wiped on container restart. Either the cont-init reconciler hasn't run yet (give it a moment after `docker restart`) or it failed. Check `docker logs <c> | grep '02-reconcile'`.
|
||||
|
||||
### Gateway starts then immediately exits (`down (exitcode 1)` in svstat)
|
||||
|
||||
Most likely the profile has no model or auth configured. The service slot is correct — the gateway itself is unconfigured. Run `hermes -p <profile> setup` first. The s6 supervisor will keep restarting it; that's the desired behavior (when you fix the config, the next attempt succeeds and stays up).
|
||||
|
||||
### Reconciler skipped a profile
|
||||
|
||||
The reconciler keys on the **presence of `SOUL.md`** as the "real profile" marker. `hermes profile create` always seeds it. If a profile dir is missing SOUL.md (stray directory, partial restore, backup-in-progress), the reconciler skips it intentionally. Add a `SOUL.md` (even empty) to opt back in.
|
||||
|
||||
### "Help, the container exits 143!"
|
||||
|
||||
Check whether something is invoking `s6-svscanctl -t` or `/run/s6/basedir/bin/halt` — both cause /init to begin stage 3 shutdown but return 143 (SIGTERM) rather than the desired exit code. This was the Phase 2 architecture pivot from A to B. For container shutdown with a real exit code, you must let the CMD (main-wrapper.sh) exit normally; do **not** try to control exit from a finish script.
|
||||
|
||||
## Related skills
|
||||
|
||||
- `hermes-agent-dev`: General hermes-agent codebase navigation
|
||||
- `hermes-tool-quirks`: Specific Hermes-tool workarounds (sed/grep/etc.) — load when debugging the s6 stack's interaction with hermes built-in tools.
|
||||
@@ -0,0 +1,173 @@
|
||||
---
|
||||
title: "Inference Sh Cli — Run 150+ AI apps (image, video, LLM) via inference.sh CLI"
|
||||
sidebar_label: "Inference Sh Cli"
|
||||
description: "Run 150+ AI apps (image, video, LLM) via inference.sh CLI"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Inference Sh Cli
|
||||
|
||||
Run 150+ AI apps (image, video, LLM) via inference.sh CLI.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/devops/inference-sh-cli` |
|
||||
| Path | `optional-skills/devops\inference-sh-cli` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | okaris |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `AI`, `image-generation`, `video`, `LLM`, `search`, `inference`, `FLUX`, `Veo`, `Claude` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# inference.sh CLI
|
||||
|
||||
Run 150+ AI apps in the cloud with a simple CLI. No GPU required.
|
||||
|
||||
All commands use the **terminal tool** to run `infsh` commands.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks to generate images (FLUX, Reve, Seedream, Grok, Gemini image)
|
||||
- User asks to generate video (Veo, Wan, Seedance, OmniHuman)
|
||||
- User asks about inference.sh or infsh
|
||||
- User wants to run AI apps without managing individual provider APIs
|
||||
- User asks for AI-powered search (Tavily, Exa)
|
||||
- User needs avatar/lipsync generation
|
||||
|
||||
## Prerequisites
|
||||
|
||||
The `infsh` CLI must be installed and authenticated. Check with:
|
||||
|
||||
```bash
|
||||
infsh me
|
||||
```
|
||||
|
||||
If not installed:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://cli.inference.sh | sh
|
||||
infsh login
|
||||
```
|
||||
|
||||
See `references/authentication.md` for full setup details.
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Always Search First
|
||||
|
||||
Never guess app names — always search to find the correct app ID:
|
||||
|
||||
```bash
|
||||
infsh app list --search flux
|
||||
infsh app list --search video
|
||||
infsh app list --search image
|
||||
```
|
||||
|
||||
### 2. Run an App
|
||||
|
||||
Use the exact app ID from the search results. Always use `--json` for machine-readable output:
|
||||
|
||||
```bash
|
||||
infsh app run <app-id> --input '{"prompt": "your prompt here"}' --json
|
||||
```
|
||||
|
||||
### 3. Parse the Output
|
||||
|
||||
The JSON output contains URLs to generated media. Present these to the user with `MEDIA:<url>` for inline display.
|
||||
|
||||
## Common Commands
|
||||
|
||||
### Image Generation
|
||||
|
||||
```bash
|
||||
# Search for image apps
|
||||
infsh app list --search image
|
||||
|
||||
# FLUX Dev with LoRA
|
||||
infsh app run falai/flux-dev-lora --input '{"prompt": "sunset over mountains", "num_images": 1}' --json
|
||||
|
||||
# Gemini image generation
|
||||
infsh app run google/gemini-2-5-flash-image --input '{"prompt": "futuristic city", "num_images": 1}' --json
|
||||
|
||||
# Seedream (ByteDance)
|
||||
infsh app run bytedance/seedream-5-lite --input '{"prompt": "nature scene"}' --json
|
||||
|
||||
# Grok Imagine (xAI)
|
||||
infsh app run xai/grok-imagine-image --input '{"prompt": "abstract art"}' --json
|
||||
```
|
||||
|
||||
### Video Generation
|
||||
|
||||
```bash
|
||||
# Search for video apps
|
||||
infsh app list --search video
|
||||
|
||||
# Veo 3.1 (Google)
|
||||
infsh app run google/veo-3-1-fast --input '{"prompt": "drone shot of coastline"}' --json
|
||||
|
||||
# Seedance (ByteDance)
|
||||
infsh app run bytedance/seedance-1-5-pro --input '{"prompt": "dancing figure", "resolution": "1080p"}' --json
|
||||
|
||||
# Wan 2.5
|
||||
infsh app run falai/wan-2-5 --input '{"prompt": "person walking through city"}' --json
|
||||
```
|
||||
|
||||
### Local File Uploads
|
||||
|
||||
The CLI automatically uploads local files when you provide a path:
|
||||
|
||||
```bash
|
||||
# Upscale a local image
|
||||
infsh app run falai/topaz-image-upscaler --input '{"image": "/path/to/photo.jpg", "upscale_factor": 2}' --json
|
||||
|
||||
# Image-to-video from local file
|
||||
infsh app run falai/wan-2-5-i2v --input '{"image": "/path/to/image.png", "prompt": "make it move"}' --json
|
||||
|
||||
# Avatar with audio
|
||||
infsh app run bytedance/omnihuman-1-5 --input '{"audio": "/path/to/audio.mp3", "image": "/path/to/face.jpg"}' --json
|
||||
```
|
||||
|
||||
### Search & Research
|
||||
|
||||
```bash
|
||||
infsh app list --search search
|
||||
infsh app run tavily/tavily-search --input '{"query": "latest AI news"}' --json
|
||||
infsh app run exa/exa-search --input '{"query": "machine learning papers"}' --json
|
||||
```
|
||||
|
||||
### Other Categories
|
||||
|
||||
```bash
|
||||
# 3D generation
|
||||
infsh app list --search 3d
|
||||
|
||||
# Audio / TTS
|
||||
infsh app list --search tts
|
||||
|
||||
# Twitter/X automation
|
||||
infsh app list --search twitter
|
||||
```
|
||||
|
||||
## Pitfalls
|
||||
|
||||
1. **Never guess app IDs** — always run `infsh app list --search <term>` first. App IDs change and new apps are added frequently.
|
||||
2. **Always use `--json`** — raw output is hard to parse. The `--json` flag gives structured output with URLs.
|
||||
3. **Check authentication** — if commands fail with auth errors, run `infsh login` or verify `INFSH_API_KEY` is set.
|
||||
4. **Long-running apps** — video generation can take 30-120 seconds. The terminal tool timeout should be sufficient, but warn the user it may take a moment.
|
||||
5. **Input format** — the `--input` flag takes a JSON string. Make sure to properly escape quotes.
|
||||
|
||||
## Reference Docs
|
||||
|
||||
- `references/authentication.md` — Setup, login, API keys
|
||||
- `references/app-discovery.md` — Searching and browsing the app catalog
|
||||
- `references/running-apps.md` — Running apps, input formats, output handling
|
||||
- `references/cli-reference.md` — Complete CLI command reference
|
||||
@@ -0,0 +1,326 @@
|
||||
---
|
||||
title: "Pinggy Tunnel — Zero-install localhost tunnels over SSH via Pinggy"
|
||||
sidebar_label: "Pinggy Tunnel"
|
||||
description: "Zero-install localhost tunnels over SSH via Pinggy"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Pinggy Tunnel
|
||||
|
||||
Zero-install localhost tunnels over SSH via Pinggy.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/devops/pinggy-tunnel` |
|
||||
| Path | `optional-skills/devops\pinggy-tunnel` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | Teknium (teknium1), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Pinggy`, `Tunnel`, `Networking`, `SSH`, `Webhook`, `Localhost` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Pinggy Tunnel Skill
|
||||
|
||||
Expose a local service (dev server, webhook receiver, MCP endpoint, demo) to the public internet using a Pinggy SSH reverse tunnel. No daemon to install — the user's stock SSH client connects to `a.pinggy.io:443` and Pinggy hands back a public HTTP/HTTPS URL.
|
||||
|
||||
Free tier: 60-minute tunnels, random subdomain, no signup. Pro tier ($3/mo) is an opt-in with a token.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks to "expose this locally", "share my dev server", "make this URL public", "tunnel port N", "get a public URL for a webhook"
|
||||
- Need to receive a webhook callback during a local task (Stripe, GitHub, Discord, AgentMail)
|
||||
- Sharing a one-off HTTP demo (MCP server, Ollama/vLLM endpoint, dashboard) with a remote party
|
||||
- The host has SSH but no `cloudflared` / `ngrok` binary, and installing one would be overkill
|
||||
|
||||
If the host already has `cloudflared` configured, prefer the `cloudflared-quick-tunnel` skill — Cloudflare quick tunnels don't expire after 60 minutes.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- `ssh` on PATH (`ssh -V`). Default on Linux, macOS, and Windows 10+. No other install.
|
||||
- A local service listening on `127.0.0.1:<port>` before the tunnel starts. Pinggy will return URLs but they'll 502 until the local origin is up.
|
||||
|
||||
Optional:
|
||||
|
||||
- `PINGGY_TOKEN` env var for paid Pro features (persistent subdomain, custom domain, multiple tunnels, no 60-minute cap). Free tier needs no credentials.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
# Plain HTTP/HTTPS tunnel for port 8000 (free tier)
|
||||
ssh -p 443 -o StrictHostKeyChecking=no -o ServerAliveInterval=30 \
|
||||
-R0:localhost:8000 free@a.pinggy.io
|
||||
|
||||
# TCP tunnel (databases, raw SSH, etc.)
|
||||
ssh -p 443 -o StrictHostKeyChecking=no -R0:localhost:5432 tcp@a.pinggy.io
|
||||
|
||||
# TLS tunnel (Pinggy can't decrypt — bring your own certs at origin)
|
||||
ssh -p 443 -o StrictHostKeyChecking=no -R0:localhost:443 tls@a.pinggy.io
|
||||
|
||||
# Basic auth gate (b:user:pass)
|
||||
ssh -p 443 -o StrictHostKeyChecking=no -R0:localhost:8000 \
|
||||
"b:admin:secret+free@a.pinggy.io"
|
||||
|
||||
# Bearer token gate (k:token)
|
||||
ssh -p 443 -o StrictHostKeyChecking=no -R0:localhost:8000 \
|
||||
"k:mysecrettoken+free@a.pinggy.io"
|
||||
|
||||
# IP whitelist (w:CIDR)
|
||||
ssh -p 443 -o StrictHostKeyChecking=no -R0:localhost:8000 \
|
||||
"w:203.0.113.0/24+free@a.pinggy.io"
|
||||
|
||||
# Enable CORS + force HTTPS redirect
|
||||
ssh -p 443 -o StrictHostKeyChecking=no -R0:localhost:8000 \
|
||||
"co+x:https+free@a.pinggy.io"
|
||||
|
||||
# Pro tier (persistent URL, no 60-min cap)
|
||||
ssh -p 443 -o StrictHostKeyChecking=no -R0:localhost:8000 "$PINGGY_TOKEN+a.pinggy.io"
|
||||
```
|
||||
|
||||
## Procedure — Start a Tunnel and Get the URL
|
||||
|
||||
The model SHOULD use the `terminal` tool. The tunnel must stay alive for the duration of the share, so run it as a background process and parse the public URL from stdout.
|
||||
|
||||
### 1. Confirm a local origin is up
|
||||
|
||||
```bash
|
||||
curl -sI http://127.0.0.1:8000/ | head -1
|
||||
# expect HTTP/1.x 200 (or any non-connection-refused response)
|
||||
```
|
||||
|
||||
If nothing is listening yet, start it first (e.g. `python -m http.server 8000 --bind 127.0.0.1`). Pinggy will happily return a URL pointed at nothing — the user will see 502 until the origin comes up.
|
||||
|
||||
### 2. Launch the tunnel as a background process
|
||||
|
||||
Use `terminal(background=True)` and capture output to a logfile (Pinggy prints the URLs on stdout, then keeps the connection open):
|
||||
|
||||
```bash
|
||||
LOG=/tmp/pinggy-8000.log
|
||||
nohup ssh -p 443 \
|
||||
-o StrictHostKeyChecking=no \
|
||||
-o UserKnownHostsFile=/dev/null \
|
||||
-o ServerAliveInterval=30 \
|
||||
-o ServerAliveCountMax=3 \
|
||||
-R0:localhost:8000 free@a.pinggy.io \
|
||||
> "$LOG" 2>&1 &
|
||||
echo $! > /tmp/pinggy-8000.pid
|
||||
```
|
||||
|
||||
`StrictHostKeyChecking=no` + `UserKnownHostsFile=/dev/null` skips the first-run host-key prompt. `ServerAliveInterval=30` keeps the SSH session from getting torn down by an idle NAT.
|
||||
|
||||
### 3. Parse the URL out of the log
|
||||
|
||||
```bash
|
||||
sleep 4
|
||||
grep -oE 'https://[a-z0-9-]+\.[a-z]+\.pinggy\.link' /tmp/pinggy-8000.log | head -1
|
||||
```
|
||||
|
||||
Expected output looks like:
|
||||
|
||||
```
|
||||
You are not authenticated.
|
||||
Your tunnel will expire in 60 minutes.
|
||||
http://yqycl-98-162-69-48.a.free.pinggy.link
|
||||
https://yqycl-98-162-69-48.a.free.pinggy.link
|
||||
```
|
||||
|
||||
Hand the `https://...pinggy.link` URL to the user.
|
||||
|
||||
### 4. Verify
|
||||
|
||||
```bash
|
||||
curl -sI https://<the-url>/ | head -3
|
||||
# expect 200/302/whatever the local origin actually returns
|
||||
```
|
||||
|
||||
If you get `502 Bad Gateway`, the SSH session is up but the local origin isn't listening — fix step 1 first.
|
||||
|
||||
### 5. Teardown
|
||||
|
||||
```bash
|
||||
kill "$(cat /tmp/pinggy-8000.pid)"
|
||||
# or, if the pid file got lost:
|
||||
pkill -f 'ssh -p 443 .* free@a\.pinggy\.io'
|
||||
```
|
||||
|
||||
If you have a session_id from `terminal(background=True)`, prefer `process(action='kill', session_id=...)`.
|
||||
|
||||
## Access Control via Username Keywords
|
||||
|
||||
Pinggy stacks control flags into the SSH username separated by `+`. Always quote the whole `user@host` argument when it contains a `+`:
|
||||
|
||||
| Keyword | Effect |
|
||||
|---------|--------|
|
||||
| `b:user:pass` | HTTP Basic auth gate |
|
||||
| `k:token` | Bearer-token header gate (`Authorization: Bearer <token>`) |
|
||||
| `w:CIDR` | IP whitelist (single IP or CIDR, repeatable) |
|
||||
| `co` | Add `Access-Control-Allow-Origin: *` (CORS) |
|
||||
| `x:https` | Force HTTPS — auto-redirect HTTP to HTTPS |
|
||||
| `a:Name:Value` | Add request header |
|
||||
| `u:Name:Value` | Update request header |
|
||||
| `r:Name` | Remove request header |
|
||||
| `qr` | Print a QR code of the URL to stdout (handy for mobile sharing) |
|
||||
|
||||
Combine freely: `"b:admin:secret+co+x:https+free@a.pinggy.io"`.
|
||||
|
||||
## Web Debugger (optional)
|
||||
|
||||
Pinggy can mirror the inbound traffic to `localhost:4300` for inspection. Add a local forward to the SSH command:
|
||||
|
||||
```bash
|
||||
ssh -p 443 -L4300:localhost:4300 -R0:localhost:8000 free@a.pinggy.io
|
||||
```
|
||||
|
||||
Then open `http://localhost:4300` in a browser to see live request/response pairs.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **60-minute hard cap on the free tier.** The SSH session terminates at the 60-minute mark; the URL goes dead. For longer shares, either use `PINGGY_TOKEN` (Pro) or auto-restart with a shell loop (note that the URL changes on every restart for free-tier).
|
||||
- **Free-tier URL is random and changes on restart.** Don't bookmark it, don't paste it into a config file. Re-parse from the log each time.
|
||||
- **Concurrent free tunnels are limited to one per source IP.** Starting a second tunnel from the same machine usually kills the first. Pro tier lifts this.
|
||||
- **`+` in usernames must be quoted.** Bare `ssh ... b:admin:secret+free@a.pinggy.io` works in bash but breaks under shells that treat `+` specially or when assembled programmatically. Always wrap in double quotes.
|
||||
- **Don't tunnel anything sensitive without an access-control flag.** A bare HTTP tunnel is reachable by anyone with the URL. Use `b:`, `k:`, or `w:` for non-public services.
|
||||
- **`process(action='log')` may miss SSH banner output.** Pinggy prints the URLs and then the SSH session goes interactive. Always redirect to a logfile and `grep` the file directly — same pattern as `cloudflared-quick-tunnel`.
|
||||
- **Host-key prompt on first run.** Default OpenSSH config asks the user to accept Pinggy's host key. Always pass `-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null` for unattended runs.
|
||||
- **TCP and TLS tunnels return a `<subdomain>.a.pinggy.online:<port>` pair, not an https URL.** Parse with a different regex (`tcp://` and a port). Don't assume every Pinggy tunnel is HTTP.
|
||||
- **Pro mode requires the token as the username, not a flag.** Use `"$PINGGY_TOKEN+a.pinggy.io"` (no `free@`). With a token you can also add `:persistent` for a stable subdomain — see `pinggy.io/docs/`.
|
||||
|
||||
## Recipes
|
||||
|
||||
Composite patterns combining a local origin with a Pinggy tunnel. Each recipe is self-contained — start the origin, start the tunnel, parse the URL, hand it back to the user.
|
||||
|
||||
### Recipe 1 — Receive a webhook callback
|
||||
|
||||
Use this when an external service (Stripe, GitHub, Discord, AgentMail, etc.) needs to POST to a publicly reachable URL during a local task.
|
||||
|
||||
```bash
|
||||
# 1. Tiny capturing server: every request gets appended to /tmp/webhook-hits.log
|
||||
cat >/tmp/webhook-server.py <<'PY'
|
||||
import http.server, json, datetime, pathlib
|
||||
LOG = pathlib.Path("/tmp/webhook-hits.log")
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def _capture(self):
|
||||
n = int(self.headers.get("content-length") or 0)
|
||||
body = self.rfile.read(n).decode("utf-8", "replace") if n else ""
|
||||
rec = {"t": datetime.datetime.utcnow().isoformat(), "path": self.path,
|
||||
"method": self.command, "headers": dict(self.headers), "body": body}
|
||||
with LOG.open("a") as f: f.write(json.dumps(rec) + "\n")
|
||||
self.send_response(200); self.send_header("content-type","application/json")
|
||||
self.end_headers(); self.wfile.write(b'{"ok":true}\n')
|
||||
def do_GET(self): self._capture()
|
||||
def do_POST(self): self._capture()
|
||||
def log_message(self,*a,**k): pass
|
||||
http.server.HTTPServer(("127.0.0.1", 18080), H).serve_forever()
|
||||
PY
|
||||
nohup python /tmp/webhook-server.py >/tmp/webhook-server.log 2>&1 &
|
||||
echo $! >/tmp/webhook-server.pid
|
||||
|
||||
# 2. Tunnel — bearer-token-gate so randos can't pollute the capture log
|
||||
nohup ssh -p 443 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
|
||||
-o ServerAliveInterval=30 \
|
||||
-R0:localhost:18080 "k:$(openssl rand -hex 12)+free@a.pinggy.io" \
|
||||
>/tmp/webhook-pinggy.log 2>&1 &
|
||||
echo $! >/tmp/webhook-pinggy.pid
|
||||
sleep 5
|
||||
URL=$(grep -oE 'https://[a-z0-9-]+\.[a-z]+\.pinggy\.link' /tmp/webhook-pinggy.log | head -1)
|
||||
echo "Webhook URL: $URL"
|
||||
|
||||
# 3. While the agent works, watch hits land
|
||||
tail -f /tmp/webhook-hits.log
|
||||
```
|
||||
|
||||
Hand `$URL` to the service that needs to call you. Teardown: `kill $(cat /tmp/webhook-server.pid) $(cat /tmp/webhook-pinggy.pid)`.
|
||||
|
||||
### Recipe 2 — Expose an MCP server over HTTP/SSE
|
||||
|
||||
Use when a remote MCP client (Claude Desktop on another machine, a teammate's editor, etc.) needs to reach an MCP server running on the local box. Only works for MCP servers that speak HTTP transport — stdio-mode servers can't be tunneled.
|
||||
|
||||
```bash
|
||||
# 1. Start the MCP server in HTTP mode (example: a FastMCP server on port 8765)
|
||||
nohup python my_mcp_server.py --transport http --port 8765 \
|
||||
>/tmp/mcp-server.log 2>&1 &
|
||||
echo $! >/tmp/mcp-server.pid
|
||||
|
||||
# 2. Tunnel with a bearer token — MCP traffic should not be open to the internet
|
||||
TOKEN=$(openssl rand -hex 16)
|
||||
nohup ssh -p 443 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
|
||||
-o ServerAliveInterval=30 \
|
||||
-R0:localhost:8765 "k:$TOKEN+free@a.pinggy.io" \
|
||||
>/tmp/mcp-pinggy.log 2>&1 &
|
||||
echo $! >/tmp/mcp-pinggy.pid
|
||||
sleep 5
|
||||
URL=$(grep -oE 'https://[a-z0-9-]+\.[a-z]+\.pinggy\.link' /tmp/mcp-pinggy.log | head -1)
|
||||
echo "MCP URL: $URL"
|
||||
echo "Bearer token: $TOKEN"
|
||||
```
|
||||
|
||||
The remote client connects to `$URL` with `Authorization: Bearer $TOKEN`. Hermes' own native MCP client config: `{"transport": "http", "url": "<URL>", "headers": {"Authorization": "Bearer <TOKEN>"}}`.
|
||||
|
||||
### Recipe 3 — Expose a local LLM endpoint (Ollama / vLLM / llama.cpp)
|
||||
|
||||
Share a local model with a remote caller (another agent, a phone, a teammate). Ollama listens on `:11434`, vLLM and llama.cpp typically on `:8000`.
|
||||
|
||||
```bash
|
||||
# Pre-req: the model server is already running on 127.0.0.1:11434 (Ollama default)
|
||||
TOKEN=$(openssl rand -hex 16)
|
||||
nohup ssh -p 443 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
|
||||
-o ServerAliveInterval=30 \
|
||||
-R0:localhost:11434 "k:$TOKEN+co+free@a.pinggy.io" \
|
||||
>/tmp/llm-pinggy.log 2>&1 &
|
||||
echo $! >/tmp/llm-pinggy.pid
|
||||
sleep 5
|
||||
URL=$(grep -oE 'https://[a-z0-9-]+\.[a-z]+\.pinggy\.link' /tmp/llm-pinggy.log | head -1)
|
||||
echo "Endpoint: $URL"
|
||||
echo "Token: $TOKEN"
|
||||
|
||||
# Verify
|
||||
curl -s "$URL/api/tags" -H "Authorization: Bearer $TOKEN" | head
|
||||
```
|
||||
|
||||
`co` enables CORS so a browser caller can hit the endpoint. Drop `co` for backend-only callers. For an OpenAI-compatible vLLM/llama.cpp endpoint, callers use base URL `$URL/v1` with `Authorization: Bearer $TOKEN` — but note Pinggy strips/replaces nothing in the body, so the model server itself sees Pinggy's token; the local server should be configured to ignore auth (it's already on `127.0.0.1`) and let Pinggy do the gating.
|
||||
|
||||
### Recipe 4 — Share a dev server with a one-shot password
|
||||
|
||||
The fastest "let a teammate poke at my running app" pattern. Random password, prints once, dies when you Ctrl-C.
|
||||
|
||||
```bash
|
||||
PASS=$(openssl rand -base64 12 | tr -d '+/=' | head -c 12)
|
||||
echo "Dev server password: $PASS"
|
||||
ssh -p 443 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
|
||||
-o ServerAliveInterval=30 \
|
||||
-R0:localhost:3000 "b:dev:$PASS+co+x:https+free@a.pinggy.io"
|
||||
# URL prints to the terminal. Share URL + password. Ctrl-C to tear down.
|
||||
```
|
||||
|
||||
`b:dev:$PASS` gates the URL with HTTP Basic auth. `x:https` forces TLS. `co` adds CORS for SPA frontends.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
# End-to-end: spin up a trivial origin, tunnel it, hit it, tear down
|
||||
python -m http.server 18000 --bind 127.0.0.1 >/tmp/origin.log 2>&1 &
|
||||
ORIGIN_PID=$!
|
||||
|
||||
nohup ssh -p 443 \
|
||||
-o StrictHostKeyChecking=no \
|
||||
-o UserKnownHostsFile=/dev/null \
|
||||
-R0:localhost:18000 free@a.pinggy.io >/tmp/pinggy-verify.log 2>&1 &
|
||||
SSH_PID=$!
|
||||
|
||||
sleep 5
|
||||
URL=$(grep -oE 'https://[a-z0-9-]+\.[a-z]+\.pinggy\.link' /tmp/pinggy-verify.log | head -1)
|
||||
echo "URL: $URL"
|
||||
curl -sI "$URL/" | head -1
|
||||
|
||||
kill "$SSH_PID" "$ORIGIN_PID"
|
||||
```
|
||||
|
||||
Expected: a `pinggy.link` URL and `HTTP/2 200` on the curl head.
|
||||
@@ -0,0 +1,133 @@
|
||||
---
|
||||
title: "Setup Wizard Generator — Generate a bash wizard guiding a human through manual setup"
|
||||
sidebar_label: "Setup Wizard Generator"
|
||||
description: "Generate a bash wizard guiding a human through manual setup"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Setup Wizard Generator
|
||||
|
||||
Generate a bash wizard guiding a human through manual setup.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/devops/setup-wizard-generator` |
|
||||
| Path | `optional-skills/devops\setup-wizard-generator` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Matt Pocock (mattpocock/skills, wizard) + Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `wizard`, `setup`, `onboarding`, `credentials`, `secrets`, `migration`, `bash`, `human-in-the-loop` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Setup Wizard Generator
|
||||
|
||||
Generates an interactive bash **wizard**: a script that walks a human, step
|
||||
by step, through a manual procedure that is tedious to do by hand and tedious
|
||||
to re-explain every time. It opens each URL, says exactly what to click and
|
||||
copy, captures the values, writes them where they belong (`.env`, GitHub
|
||||
secrets), confirms at every stage, and shows how many stages are left.
|
||||
|
||||
Ported from mattpocock/skills' MIT-licensed `wizard` skill.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Provisioning infrastructure or third-party services (Stripe, Supabase,
|
||||
DNS, OAuth apps) where only a human can click through the dashboard
|
||||
- Setting up credentials, CI secrets, or repo variables
|
||||
- One-off migrations or cutovers with irreversible human-gated steps
|
||||
- Any procedure the user will hand to a teammate to run
|
||||
|
||||
Do NOT use for steps the agent can perform itself — do those directly.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- `bash`; `gh` CLI only if stages write GitHub secrets/variables
|
||||
- The library template: `templates/template.sh` in this skill's directory
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Scope the procedure
|
||||
|
||||
Work out every manual step the human must take and every value captured
|
||||
along the way. Read the repo first, don't ask cold:
|
||||
|
||||
- Setup: `.env`, `.env.example`, `README`, `docker-compose*`, framework
|
||||
config, and `.github/workflows/*` (every `secrets.*` / `vars.*` reference
|
||||
is a value the wizard must produce).
|
||||
- Migration/cutover: the current state, the target state, and the
|
||||
irreversible actions between them.
|
||||
|
||||
Show the user the ordered stage list and the values each produces; they may
|
||||
add, drop, or reorder. Done when every stage is named in order and, for each
|
||||
captured value, you know (a) where the human gets it, (b) where it's written
|
||||
(`.env`, a GitHub secret, both, or nowhere), and (c) whether it's secret
|
||||
(hidden entry) or public.
|
||||
|
||||
### 2. Map each stage's journey
|
||||
|
||||
For each stage, write the precise path a human follows: which URL to open,
|
||||
what to do there, where the value is shown — e.g. "Dashboard → Developers →
|
||||
API keys → Reveal test key → copy". Where you don't know the current UI or
|
||||
exact command, say so and check the docs or ask — never invent steps that
|
||||
may not exist.
|
||||
|
||||
### 3. Author the wizard
|
||||
|
||||
Copy `templates/template.sh` (from this skill's directory) to the target
|
||||
path. Replace the example stage with one `stage` per step, in dependency
|
||||
order. Set `TOTAL_STAGES` to the number of stages you wrote.
|
||||
|
||||
Library helpers: `stage`, `say`/`step`/`note`/`warn`, `open_url`,
|
||||
`ask`/`ask_secret`, `write_env`, `set_secret`/`set_var`, `pause`/`confirm`,
|
||||
`banner`, `finish`. The library above the `STAGES` marker is identical in
|
||||
every wizard — never hand-edit it; that consistency is the point.
|
||||
|
||||
Hold the bar the template sets: open the URL before asking for its value,
|
||||
`ask_secret` for anything secret, `write_env` every persisted value,
|
||||
`set_secret` only what CI actually needs, and `confirm` before anything
|
||||
irreversible. Each `stage` clears the screen — keep one focused task per
|
||||
stage so nothing the human needs scrolls away.
|
||||
|
||||
A wizard is ephemeral by default: save it to a scratch or `scripts/` path,
|
||||
delete it when the job's done. Commit it only when the user wants a
|
||||
repeatable setup path living in the repo.
|
||||
|
||||
### 4. Verify and hand off
|
||||
|
||||
- `bash -n <script>`; run `shellcheck` if available; `chmod +x <script>`.
|
||||
- Do NOT run it end-to-end yourself: it opens browsers and blocks on human
|
||||
input. Trace it statically: every value from step 1 is captured and lands
|
||||
where step 1 said, and every `set_secret` name exactly matches a
|
||||
`secrets.*` reference in CI.
|
||||
- Tell the user how to run it. If it's repeatable, commit it and link it
|
||||
from the README.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
1. **Editing the library section.** Everything above the `STAGES` marker is
|
||||
the wizard library; author only below it.
|
||||
2. **Inventing dashboard paths.** Third-party UIs drift. If unsure of the
|
||||
click path, verify against current docs or flag it as approximate.
|
||||
3. **`set_secret` for values CI doesn't use.** Only push to GitHub secrets
|
||||
what a workflow actually references.
|
||||
4. **Running the wizard yourself.** It blocks on human input; static tracing
|
||||
plus `bash -n` is the verification.
|
||||
5. **One mega-stage.** Screen clearing per stage means a long stage scrolls
|
||||
critical instructions away; split it.
|
||||
|
||||
## Verification
|
||||
|
||||
- [ ] Stage list confirmed with the user before authoring
|
||||
- [ ] `bash -n` passes; script is executable
|
||||
- [ ] Every captured value traced to its declared destination
|
||||
- [ ] Every `set_secret` name matches a CI `secrets.*` reference
|
||||
- [ ] Library section untouched from the template
|
||||
@@ -0,0 +1,126 @@
|
||||
---
|
||||
title: "Watchers — Poll RSS, JSON APIs, and GitHub with watermark dedup"
|
||||
sidebar_label: "Watchers"
|
||||
description: "Poll RSS, JSON APIs, and GitHub with watermark dedup"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Watchers
|
||||
|
||||
Poll RSS, JSON APIs, and GitHub with watermark dedup.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/devops/watchers` |
|
||||
| Path | `optional-skills/devops\watchers` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `cron`, `polling`, `rss`, `github`, `http`, `automation`, `monitoring` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Watchers
|
||||
|
||||
Poll external sources on an interval and react only to new items. Three ready-made scripts plus a shared watermark helper; wire them into a cron job (or run them ad-hoc from the terminal).
|
||||
|
||||
## When to Use
|
||||
|
||||
- User wants to watch an RSS/Atom feed and be notified of new entries
|
||||
- User wants to watch a GitHub repo's issues / pulls / releases / commits
|
||||
- User wants to poll an arbitrary JSON endpoint and get notified on new items
|
||||
- User asks for "a watcher for X" or "notify me when X changes"
|
||||
|
||||
## Mental model
|
||||
|
||||
A watcher is just a script that:
|
||||
|
||||
1. Fetches data from the external source
|
||||
2. Compares against a watermark file of previously-seen IDs
|
||||
3. Writes the new watermark back
|
||||
4. Prints new items to stdout (or nothing on no-change)
|
||||
|
||||
The scripts below handle all three. The agent runs them via the terminal tool — from a cron job, a webhook, or an interactive chat — and reports what's new.
|
||||
|
||||
## Ready-made scripts
|
||||
|
||||
All three live in `$HERMES_HOME/skills/devops/watchers/scripts/` once the skill is installed. Each reads `WATCHER_STATE_DIR` (defaults to `$HERMES_HOME/watcher-state/`) for its state file, keyed by the `--name` argument.
|
||||
|
||||
| Script | What it watches | Dedup key |
|
||||
|---|---|---|
|
||||
| `watch_rss.py` | RSS 2.0 or Atom feed URL | `<guid>` / `<id>` |
|
||||
| `watch_http_json.py` | Any JSON endpoint returning a list of objects | Configurable id field |
|
||||
| `watch_github.py` | GitHub issues / pulls / releases / commits for a repo | `id` / `sha` |
|
||||
|
||||
All three:
|
||||
|
||||
- First run records a baseline — never replays existing feed
|
||||
- Watermark is a bounded ID set (max 500) to cap memory
|
||||
- Output format: `## <title>\n<url>\n\n<optional body>` per item
|
||||
- Empty stdout on no-new — the caller treats that as silent
|
||||
- Non-zero exit on fetch errors
|
||||
|
||||
## Usage
|
||||
|
||||
Run a watcher directly from the terminal tool:
|
||||
|
||||
```bash
|
||||
python $HERMES_HOME/skills/devops/watchers/scripts/watch_rss.py \
|
||||
--name hn --url https://news.ycombinator.com/rss --max 5
|
||||
```
|
||||
|
||||
Watch a GitHub repo (set `GITHUB_TOKEN` in `${HERMES_HOME:-~/.hermes}/.env` to avoid the 60 req/hr anonymous rate limit):
|
||||
|
||||
```bash
|
||||
python $HERMES_HOME/skills/devops/watchers/scripts/watch_github.py \
|
||||
--name hermes-issues --repo NousResearch/hermes-agent --scope issues
|
||||
```
|
||||
|
||||
Poll an arbitrary JSON API:
|
||||
|
||||
```bash
|
||||
python $HERMES_HOME/skills/devops/watchers/scripts/watch_http_json.py \
|
||||
--name api --url https://api.example.com/events \
|
||||
--id-field event_id --items-path data.events
|
||||
```
|
||||
|
||||
## Wiring into cron
|
||||
|
||||
Ask the agent to schedule a cron job with a prompt like:
|
||||
|
||||
> Every 15 minutes, run `watch_rss.py --name hn --url https://news.ycombinator.com/rss`. If it prints anything, summarize the headlines and deliver them. If it prints nothing, stay silent.
|
||||
|
||||
The agent invokes the script via the terminal tool inside the cron job's agent loop; no changes to cron's built-in `--script` flag are needed.
|
||||
|
||||
## State files
|
||||
|
||||
Every watcher writes `$HERMES_HOME/watcher-state/<name>.json`. Inspect:
|
||||
|
||||
```bash
|
||||
cat $HERMES_HOME/watcher-state/hn.json
|
||||
```
|
||||
|
||||
Force a replay (next run treated as first poll):
|
||||
|
||||
```bash
|
||||
rm $HERMES_HOME/watcher-state/hn.json
|
||||
```
|
||||
|
||||
## Writing your own
|
||||
|
||||
All three scripts use the same template: load watermark, fetch, diff, save, emit. `scripts/_watermark.py` is the shared helper; import it to get atomic writes + bounded ID set + first-run baseline for free. See any of the three reference scripts for how little boilerplate it takes.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
1. **Printing a "no new items" header every tick.** Callers rely on empty stdout = silent. If you print anything on an empty delta, you spam the channel. The shipped scripts handle this; custom scripts must too.
|
||||
2. **Expecting the first run to emit items.** It won't — first run records a baseline. If you need an initial digest, delete the state file after the first run or add a `--prime-with-latest N` flag in your own script.
|
||||
3. **Unbounded watermark growth.** The shared helper caps at 500 IDs. Raise it for high-churn feeds; lower it on constrained filesystems.
|
||||
4. **Putting the state dir where the agent's sandbox can't write.** `$HERMES_HOME/watcher-state/` is always writable. Docker/Modal backends may not see arbitrary host paths.
|
||||
@@ -0,0 +1,209 @@
|
||||
---
|
||||
title: "Adversarial Ux Test — Roleplay a hostile user to find and triage UX pain points"
|
||||
sidebar_label: "Adversarial Ux Test"
|
||||
description: "Roleplay a hostile user to find and triage UX pain points"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Adversarial Ux Test
|
||||
|
||||
Roleplay a hostile user to find and triage UX pain points.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/dogfood/adversarial-ux-test` |
|
||||
| Path | `optional-skills/dogfood\adversarial-ux-test` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Omni @ Comelse |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `qa`, `ux`, `testing`, `adversarial`, `dogfood`, `personas`, `user-testing` |
|
||||
| Related skills | [`dogfood`](/docs/user-guide/skills/bundled/software-development/software-development-dogfood) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Adversarial UX Test
|
||||
|
||||
Roleplay the worst-case user for your product — the person who hates technology, doesn't want your software, and will find every reason to complain. Then filter their feedback through a pragmatism layer to separate real UX problems from "I hate computers" noise.
|
||||
|
||||
Think of it as an automated "mom test" — but angry.
|
||||
|
||||
## Why This Works
|
||||
|
||||
Most QA finds bugs. This finds **friction**. A technically correct app can still be unusable for real humans. The adversarial persona catches:
|
||||
- Confusing terminology that makes sense to developers but not users
|
||||
- Too many steps to accomplish basic tasks
|
||||
- Missing onboarding or "aha moments"
|
||||
- Accessibility issues (font size, contrast, click targets)
|
||||
- Cold-start problems (empty states, no demo content)
|
||||
- Paywall/signup friction that kills conversion
|
||||
|
||||
The **pragmatism filter** (Phase 3) is what makes this useful instead of just entertaining. Without it, you'd add a "print this page" button to every screen because Grandpa can't figure out PDFs.
|
||||
|
||||
## How to Use
|
||||
|
||||
Tell the agent:
|
||||
```
|
||||
"Run an adversarial UX test on [URL]"
|
||||
"Be a grumpy [persona type] and test [app name]"
|
||||
"Do an asshole user test on my staging site"
|
||||
```
|
||||
|
||||
You can provide a persona or let the agent generate one based on your product's target audience.
|
||||
|
||||
## Step 1: Define the Persona
|
||||
|
||||
If no persona is provided, generate one by answering:
|
||||
|
||||
1. **Who is the HARDEST user for this product?** (age 50+, non-technical role, decades of experience doing it "the old way")
|
||||
2. **What is their tech comfort level?** (the lower the better — WhatsApp-only, paper notebooks, wife set up their email)
|
||||
3. **What is the ONE thing they need to accomplish?** (their core job, not your feature list)
|
||||
4. **What would make them give up?** (too many clicks, jargon, slow, confusing)
|
||||
5. **How do they talk when frustrated?** (blunt, sweary, dismissive, sighing)
|
||||
|
||||
### Good Persona Example
|
||||
> **"Big Mick" McAllister** — 58-year-old S&C coach. Uses WhatsApp and that's it. His "spreadsheet" is a paper notebook. "If I can't figure it out in 10 seconds I'm going back to my notebook." Needs to log session results for 25 players. Hates small text, jargon, and passwords.
|
||||
|
||||
### Bad Persona Example
|
||||
> "A user who doesn't like the app" — too vague, no constraints, no voice.
|
||||
|
||||
The persona must be **specific enough to stay in character** for 20 minutes of testing.
|
||||
|
||||
## Step 2: Become the Asshole (Browse as the Persona)
|
||||
|
||||
1. Read any available project docs for app context and URLs
|
||||
2. **Fully inhabit the persona** — their frustrations, limitations, goals
|
||||
3. Navigate to the app using browser tools
|
||||
4. **Attempt the persona's ACTUAL TASKS** (not a feature tour):
|
||||
- Can they do what they came to do?
|
||||
- How many clicks/screens to accomplish it?
|
||||
- What confuses them?
|
||||
- What makes them angry?
|
||||
- Where do they get lost?
|
||||
- What would make them give up and go back to their old way?
|
||||
|
||||
5. Test these friction categories:
|
||||
- **First impression** — would they even bother past the landing page?
|
||||
- **Core workflow** — the ONE thing they need to do most often
|
||||
- **Error recovery** — what happens when they do something wrong?
|
||||
- **Readability** — text size, contrast, information density
|
||||
- **Speed** — does it feel faster than their current method?
|
||||
- **Terminology** — any jargon they wouldn't understand?
|
||||
- **Navigation** — can they find their way back? do they know where they are?
|
||||
|
||||
6. Take screenshots of every pain point
|
||||
7. Check browser console for JS errors on every page
|
||||
|
||||
## Step 3: The Rant (Write Feedback in Character)
|
||||
|
||||
Write the feedback AS THE PERSONA — in their voice, with their frustrations. This is not a bug report. This is a real human venting.
|
||||
|
||||
```
|
||||
[PERSONA NAME]'s Review of [PRODUCT]
|
||||
|
||||
Overall: [Would they keep using it? Yes/No/Maybe with conditions]
|
||||
|
||||
THE GOOD (grudging admission):
|
||||
- [things even they have to admit work]
|
||||
|
||||
THE BAD (legitimate UX issues):
|
||||
- [real problems that would stop them from using the product]
|
||||
|
||||
THE UGLY (showstoppers):
|
||||
- [things that would make them uninstall/cancel immediately]
|
||||
|
||||
SPECIFIC COMPLAINTS:
|
||||
1. [Page/feature]: "[quote in persona voice]" — [what happened, expected]
|
||||
2. ...
|
||||
|
||||
VERDICT: "[one-line persona quote summarizing their experience]"
|
||||
```
|
||||
|
||||
## Step 4: The Pragmatism Filter (Critical — Do Not Skip)
|
||||
|
||||
Step OUT of the persona. Evaluate each complaint as a product person:
|
||||
|
||||
- **RED: REAL UX BUG** — Any user would have this problem, not just grumpy ones. Fix it.
|
||||
- **YELLOW: VALID BUT LOW PRIORITY** — Real issue but only for extreme users. Note it.
|
||||
- **WHITE: PERSONA NOISE** — "I hate computers" talking, not a product problem. Skip it.
|
||||
- **GREEN: FEATURE REQUEST** — Good idea hidden in the complaint. Consider it.
|
||||
|
||||
### Filter Criteria
|
||||
1. Would a 35-year-old competent-but-busy user have the same complaint? → RED
|
||||
2. Is this a genuine accessibility issue (font size, contrast, click targets)? → RED
|
||||
3. Is this "I want it to work like paper" resistance to digital? → WHITE
|
||||
4. Is this a real workflow inefficiency the persona stumbled on? → YELLOW or RED
|
||||
5. Would fixing this add complexity for the 80% who are fine? → WHITE
|
||||
6. Does the complaint reveal a missing onboarding moment? → GREEN
|
||||
|
||||
**This filter is MANDATORY.** Never ship raw persona complaints as tickets.
|
||||
|
||||
## Step 5: Create Tickets
|
||||
|
||||
For **RED** and **GREEN** items only:
|
||||
- Clear, actionable title
|
||||
- Include the persona's verbatim quote (entertaining + memorable)
|
||||
- The real UX issue underneath (objective)
|
||||
- A suggested fix (actionable)
|
||||
- Tag/label: "ux-review"
|
||||
|
||||
For **YELLOW** items: one catch-all ticket with all notes.
|
||||
|
||||
**WHITE** items appear in the report only. No tickets.
|
||||
|
||||
**Max 10 tickets per session** — focus on the worst issues.
|
||||
|
||||
## Step 6: Report
|
||||
|
||||
Deliver:
|
||||
1. The persona rant (Step 3) — entertaining and visceral
|
||||
2. The filtered assessment (Step 4) — pragmatic and actionable
|
||||
3. Tickets created (Step 5) — with links
|
||||
4. Screenshots of key issues
|
||||
|
||||
## Tips
|
||||
|
||||
- **One persona per session.** Don't mix perspectives.
|
||||
- **Stay in character during Steps 2-3.** Break character only at Step 4.
|
||||
- **Test the CORE WORKFLOW first.** Don't get distracted by settings pages.
|
||||
- **Empty states are gold.** New user experience reveals the most friction.
|
||||
- **The best findings are RED items the persona found accidentally** while trying to do something else.
|
||||
- **If the persona has zero complaints, your persona is too tech-savvy.** Make them older, less patient, more set in their ways.
|
||||
- **Run this before demos, launches, or after shipping a batch of features.**
|
||||
- **Register as a NEW user when possible.** Don't use pre-seeded admin accounts — the cold start experience is where most friction lives.
|
||||
- **Zero WHITE items is a signal, not a failure.** If the pragmatism filter finds no noise, your product has real UX problems, not just a grumpy persona.
|
||||
- **Check known issues in project docs AFTER the test.** If the persona found a bug that's already in the known issues list, that's actually the most damning finding — it means the team knew about it but never felt the user's pain.
|
||||
- **Subscription/paywall testing is critical.** Test with expired accounts, not just active ones. The "what happens when you can't pay" experience reveals whether the product respects users or holds their data hostage.
|
||||
- **Count the clicks to accomplish the persona's ONE task.** If it's more than 5, that's almost always a RED finding regardless of persona tech level.
|
||||
|
||||
## Example Personas by Industry
|
||||
|
||||
These are starting points — customize for your specific product:
|
||||
|
||||
| Product Type | Persona | Age | Key Trait |
|
||||
|-------------|---------|-----|-----------|
|
||||
| CRM | Retirement home director | 68 | Filing cabinet is the current CRM |
|
||||
| Photography SaaS | Rural wedding photographer | 62 | Books clients by phone, invoices on paper |
|
||||
| AI/ML Tool | Department store buyer | 55 | Burned by 3 failed tech startups |
|
||||
| Fitness App | Old-school gym coach | 58 | Paper notebook, thick fingers, bad eyes |
|
||||
| Accounting | Family bakery owner | 64 | Shoebox of receipts, hates subscriptions |
|
||||
| E-commerce | Market stall vendor | 60 | Cash only, smartphone is for calls |
|
||||
| Healthcare | Senior GP | 63 | Dictates notes, nurse handles the computer |
|
||||
| Education | Veteran teacher | 57 | Chalk and talk, worksheets in ring binders |
|
||||
|
||||
## Rules
|
||||
|
||||
- Stay in character during Steps 2-3
|
||||
- Be genuinely mean but fair — find real problems, not manufactured ones
|
||||
- The pragmatism filter (Step 4) is **MANDATORY**
|
||||
- Screenshots required for every complaint
|
||||
- Max 10 tickets per session
|
||||
- Test on staging/deployed app, not local dev
|
||||
- One persona, one session, one report
|
||||
@@ -0,0 +1,104 @@
|
||||
---
|
||||
title: "Agentmail — Use when an agent needs AgentMail CLI email inboxes"
|
||||
sidebar_label: "Agentmail"
|
||||
description: "Use when an agent needs AgentMail CLI email inboxes"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Agentmail
|
||||
|
||||
Use when an agent needs AgentMail CLI email inboxes.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/email/agentmail` |
|
||||
| Path | `optional-skills/email\agentmail` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Haakam Aujla (Haakam21), AgentMail |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Email`, `CLI`, `AgentMail`, `Communication` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# AgentMail Skill
|
||||
|
||||
AgentMail gives an agent its own email inbox for sending mail, receiving
|
||||
replies, completing email OTP flows, and running inbound email loops. Use it for
|
||||
agent-owned inboxes, not a user's existing IMAP/SMTP mailbox.
|
||||
|
||||
Use the `agentmail` CLI first. Use MCP only when the harness expects MCP tools;
|
||||
use REST only when the CLI is missing a required operation.
|
||||
|
||||
## When to Use
|
||||
|
||||
- The agent needs an email address it owns.
|
||||
- The task involves email OTP flows, replies, threads, labels, or attachments.
|
||||
- The agent needs webhook or WebSocket delivery for inbound mail.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Run commands through the `terminal` tool.
|
||||
- Install the CLI:
|
||||
|
||||
```bash
|
||||
npm install -g agentmail-cli@latest
|
||||
```
|
||||
|
||||
- Export an API key:
|
||||
|
||||
```bash
|
||||
export AGENTMAIL_API_KEY="am_..."
|
||||
```
|
||||
|
||||
No API key yet? Use [signup.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/signup.md).
|
||||
|
||||
## How to Run
|
||||
|
||||
Use `--format json` whenever another command or script needs IDs.
|
||||
|
||||
```bash
|
||||
agentmail inboxes list --format json
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
- [AgentMail agent reference](https://agentmail.md): hosted copy.
|
||||
- [AgentMail](https://agentmail.to): product landing page.
|
||||
- [Console](https://console.agentmail.to): API keys and account management.
|
||||
- [Docs](https://docs.agentmail.to): full product documentation.
|
||||
- [signup.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/signup.md): self-signup and OTP verification.
|
||||
- [core.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/core.md): inboxes, messages, threads, labels, attachments.
|
||||
- [webhooks.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/webhooks.md): events to a public HTTPS server.
|
||||
- [websockets.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/websockets.md): events to a local agent process.
|
||||
- [mcp.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/mcp.md): MCP integration.
|
||||
|
||||
## Procedure
|
||||
|
||||
1. Install `agentmail-cli@latest` and verify `agentmail inboxes list --format json`.
|
||||
2. If no API key is available, complete [signup.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/signup.md).
|
||||
3. Use [core.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/core.md) for inbox, send, read, reply, forward,
|
||||
label, thread, and attachment flows.
|
||||
4. Add [webhooks.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/webhooks.md) or
|
||||
[websockets.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/email\agentmail/references/websockets.md) only when polling is not enough.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Prefer `AGENTMAIL_API_KEY` over `--api-key`.
|
||||
- Never expose `AGENTMAIL_API_KEY` in prompts, logs, URLs, or committed files.
|
||||
- Use stable `client_id` values for retried create operations.
|
||||
- Prefer `extracted_text` or `extracted_html` for LLM input when present.
|
||||
- React to `message.received`, not messages the agent sent.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
agentmail inboxes list --format json
|
||||
```
|
||||
@@ -0,0 +1,451 @@
|
||||
---
|
||||
title: "3 Statement Model — Build integrated IS/BS/CF financial workbooks in Excel"
|
||||
sidebar_label: "3 Statement Model"
|
||||
description: "Build integrated IS/BS/CF financial workbooks in Excel"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# 3 Statement Model
|
||||
|
||||
Build integrated IS/BS/CF financial workbooks in Excel.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/finance/3-statement-model` |
|
||||
| Path | `optional-skills/finance\3-statement-model` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Anthropic (adapted by Nous Research) |
|
||||
| License | Apache-2.0 |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `finance`, `three-statement`, `income-statement`, `balance-sheet`, `cash-flow`, `excel`, `openpyxl`, `modeling` |
|
||||
| Related skills | [`excel-author`](/docs/user-guide/skills/optional/finance/finance-excel-author), [`pptx-author`](/docs/user-guide/skills/optional/finance/finance-pptx-author), [`dcf-model`](/docs/user-guide/skills/optional/finance/finance-dcf-model), [`lbo-model`](/docs/user-guide/skills/optional/finance/finance-lbo-model) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
## Environment
|
||||
|
||||
This skill assumes **headless openpyxl** — you are producing an .xlsx file on disk.
|
||||
Follow the `excel-author` skill's conventions for cell coloring, formulas, named ranges, and sensitivity tables.
|
||||
Recalculate before delivery: `python /path/to/excel-author/scripts/recalc.py ./out/model.xlsx`.
|
||||
|
||||
# 3-Statement Financial Model Template Completion
|
||||
|
||||
Complete and populate integrated financial model templates with proper linkages between Income Statement, Balance Sheet, and Cash Flow Statement.
|
||||
|
||||
## ⚠️ CRITICAL PRINCIPLES — Read Before Populating Any Template
|
||||
|
||||
**Formulas over hardcodes (non-negotiable):**
|
||||
- Every projection cell, roll-forward, linkage, and subtotal MUST be an Excel formula — never a pre-computed value
|
||||
- When using Python/openpyxl: write formula strings (`ws["D15"] = "=D14*(1+Assumptions!$B$5)"`), NOT computed results (`ws["D15"] = 12500`)
|
||||
- The ONLY cells that should contain hardcoded numbers are: (1) historical actuals, (2) assumption drivers in the Assumptions tab
|
||||
- If you find yourself computing a value in Python and writing the result to a cell — STOP. Write the formula instead.
|
||||
- Why: the model must flex when scenarios toggle or assumptions change. Hardcodes break every downstream integrity check silently.
|
||||
|
||||
**Verify step-by-step with the user:**
|
||||
1. **After mapping the template** → show the user which tabs/sections you've identified and confirm before touching any cells
|
||||
2. **After populating historicals** → show the user the historical block and confirm values/periods match source data
|
||||
3. **After building IS projections** → run the subtotal checks, show the user the projected IS, confirm before moving to BS
|
||||
4. **After building BS** → show the user the balance check (Assets = L+E) for every period, confirm before moving to CF
|
||||
5. **After building CF** → show the user the cash tie-out (CF ending cash = BS cash), confirm before finalizing
|
||||
6. **Do NOT populate the entire model end-to-end and present it complete** — break at each statement, show the work, catch errors early
|
||||
|
||||
## Formatting — Professional Blue/Grey Palette (Default unless template/user specifies otherwise)
|
||||
|
||||
**Keep colors minimal.** Use only blues and greys for cell fills. Do NOT introduce greens, yellows, oranges, or multiple accent colors — a clean model uses restraint.
|
||||
|
||||
| Element | Fill | Font |
|
||||
|---|---|---|
|
||||
| Section headers (IS / BS / CF titles) | Dark blue `#1F4E79` | White bold |
|
||||
| Column headers (FY2024A, FY2025E, etc.) | Light blue `#D9E1F2` | Black bold |
|
||||
| Input cells (historicals, assumption drivers) | Light grey `#F2F2F2` or white | Blue `#0000FF` |
|
||||
| Formula cells | White | Black |
|
||||
| Cross-tab links | White | Green `#008000` |
|
||||
| Check rows / key totals | Medium blue `#BDD7EE` | Black bold |
|
||||
|
||||
**That's 3 blues + 1 grey + white.** If the template has its own color scheme, follow the template instead.
|
||||
|
||||
Font color signals *what* a cell is (input/formula/link). Fill color signals *where* you are (header/data/check).
|
||||
|
||||
## Model Structure
|
||||
|
||||
### Identifying Template Tab Organization
|
||||
|
||||
Templates vary in their tab naming conventions and organization. Before populating, review all tabs to understand the template's structure. Below are common tab names and their typical contents:
|
||||
|
||||
| Common Tab Names | Contents to Look For |
|
||||
|------------------|----------------------|
|
||||
| IS, P&L, Income Statement | Income Statement |
|
||||
| BS, Balance Sheet | Balance Sheet |
|
||||
| CF, CFS, Cash Flow | Cash Flow Statement |
|
||||
| WC, Working Capital | Working Capital Schedule |
|
||||
| DA, D&A, Depreciation, PP&E | Depreciation & Amortization Schedule |
|
||||
| Debt, Debt Schedule | Debt Schedule |
|
||||
| NOL, Tax, DTA | Net Operating Loss Schedule |
|
||||
| Assumptions, Inputs, Drivers | Driver assumptions and inputs |
|
||||
| Checks, Audit, Validation | Error-checking dashboard |
|
||||
|
||||
**Template Review Checklist**
|
||||
- Identify which tabs exist in the template (not all templates include every schedule)
|
||||
- Note any template-specific tabs not listed above
|
||||
- Understand tab dependencies (e.g., which schedules feed into the main statements)
|
||||
- Locate input cells vs. formula cells on each tab
|
||||
|
||||
### Understanding Template Structure
|
||||
|
||||
Before populating a template, familiarize yourself with its existing layout to ensure data is entered in the correct locations and formulas remain intact.
|
||||
|
||||
**Identifying Row Structure**
|
||||
- Locate the model title at top of each tab
|
||||
- Identify section headers and their visual separation
|
||||
- Find the units row indicating $ millions, %, x, etc.
|
||||
- Note column headers distinguishing Actuals vs. Estimates periods
|
||||
- Confirm period labels (e.g., FY2024A, FY2025E)
|
||||
- Identify input cells vs. formula cells (typically distinguished by font color)
|
||||
|
||||
**Identifying Column Structure**
|
||||
- Confirm line item labels in leftmost column
|
||||
- Verify historical years precede projection years
|
||||
- Note the visual border separating historical from projected periods
|
||||
- Check for consistent column order across all tabs
|
||||
|
||||
**Working with Named Ranges**
|
||||
Templates often use named ranges for key inputs and outputs. Before entering data:
|
||||
- Review existing named ranges in the template (Formulas → Name Manager in Excel)
|
||||
- Common named ranges include: Revenue growth rates, cost percentages, key outputs (Net Income, EBITDA, Total Debt, Cash), scenario selector cell
|
||||
- Ensure inputs are entered in cells that feed into these named ranges
|
||||
|
||||
### Projection Period
|
||||
- Templates typically project 5 years forward from last historical year
|
||||
- Verify historical (A) vs. projected (E) columns are clearly separated
|
||||
- Confirm columns use fiscal year notation (e.g., FY2024A, FY2025E)
|
||||
|
||||
## Margin Analysis
|
||||
|
||||
**Note: The following margin analysis should only be performed if prompted by the user or if the template explicitly requires it. If no prompt is given, skip this section.**
|
||||
|
||||
Calculate and display profitability margins on the Income Statement (IS) tab to track operational efficiency and enable peer comparison.
|
||||
|
||||
### Core Margins to Include
|
||||
|
||||
| Margin | Formula | What It Measures |
|
||||
|--------|---------|------------------|
|
||||
| Gross Margin | Gross Profit / Revenue | Pricing power, production efficiency |
|
||||
| EBITDA Margin | EBITDA / Revenue | Core operating profitability |
|
||||
| EBIT Margin | EBIT / Revenue | Operating profitability after D&A |
|
||||
| Net Income Margin | Net Income / Revenue | Bottom-line profitability |
|
||||
|
||||
### Income Statement Layout with Margins
|
||||
|
||||
Display margin percentages directly below each profit line item:
|
||||
- Gross Margin % below Gross Profit
|
||||
- EBIT Margin % below EBIT
|
||||
- EBITDA Margin % below EBITDA
|
||||
- Net Income Margin % below Net Income
|
||||
|
||||
## Credit Metrics
|
||||
|
||||
**Note: The following Credit analysis should only be performed if prompted by the user or if the template explicitly requires it. If no prompt is given, skip this section.**
|
||||
|
||||
Calculate and display credit/leverage metrics on the Balance Sheet (BS) tab to assess financial health, debt capacity, and covenant compliance.
|
||||
|
||||
### Core Credit Metrics to Include
|
||||
|
||||
| Metric | Formula | What It Measures |
|
||||
|--------|---------|------------------|
|
||||
| Total Debt / EBITDA | Total Debt / LTM EBITDA | Leverage multiple |
|
||||
| Net Debt / EBITDA | (Total Debt - Cash) / LTM EBITDA | Leverage net of cash |
|
||||
| Interest Coverage | EBITDA / Interest Expense | Ability to service debt |
|
||||
| Debt / Total Cap | Total Debt / (Total Debt + Equity) | Capital structure |
|
||||
| Debt / Equity | Total Debt / Total Equity | Financial leverage |
|
||||
| Current Ratio | Current Assets / Current Liabilities | Short-term liquidity |
|
||||
| Quick Ratio | (Current Assets - Inventory) / Current Liabilities | Immediate liquidity |
|
||||
|
||||
### Credit Metric Hierarchy Checks
|
||||
|
||||
Validate that Upside shows strongest credit profile:
|
||||
- Leverage: Upside < Base < Downside (lower is better)
|
||||
- Coverage: Upside > Base > Downside (higher is better)
|
||||
- Liquidity: Upside > Base > Downside (higher is better)
|
||||
|
||||
### Covenant Compliance Tracking
|
||||
|
||||
If debt covenants are known, add explicit compliance checks comparing actual metrics to covenant thresholds.
|
||||
|
||||
## Scenario Analysis (Base / Upside / Downside)
|
||||
|
||||
Use a scenario toggle (dropdown) in the Assumptions tab with CHOOSE or INDEX/MATCH formulas.
|
||||
|
||||
| Scenario | Description |
|
||||
|----------|-------------|
|
||||
| Base Case | Management guidance or consensus estimates |
|
||||
| Upside Case | Above-guidance growth, margin expansion |
|
||||
| Downside Case | Below-trend growth, margin compression |
|
||||
|
||||
**Key Drivers to Sensitize**: Revenue growth, Gross margin, SG&A %, DSO/DIO/DPO, CapEx %, Interest rate, Tax rate.
|
||||
|
||||
**Scenario Audit Checks**: Toggle switches all statements, BS balances in all scenarios, Cash ties out, Hierarchy holds (Upside > Base > Downside for NI, EBITDA, FCF, margins).
|
||||
|
||||
## SEC Filings Data Extraction
|
||||
|
||||
If the template specifically requires pulling data from SEC filings (10-K, 10-Q), see [references/sec-filings.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/finance\3-statement-model/references/sec-filings.md) for detailed extraction guidance. This reference is only needed when populating templates with public company data from regulatory filings.
|
||||
|
||||
## Completing Model Templates
|
||||
|
||||
This section provides general guidance for completing any 3-statement financial model template while preserving existing formulas and ensuring data integrity.
|
||||
|
||||
### Step 1: Analyze the Template Structure
|
||||
|
||||
Before entering any data, thoroughly review the template to understand its architecture:
|
||||
|
||||
**Identify Input vs. Formula Cells**
|
||||
- Look for visual cues (font color, cell shading) that distinguish input cells from formula cells
|
||||
- Common conventions: Blue font = inputs, Black font = formulas, Green font = links to other sheets
|
||||
- Use Excel's Trace Precedents/Dependents (Formulas → Trace Precedents) to understand cell relationships
|
||||
- Check for named ranges that may control key inputs (Formulas → Name Manager)
|
||||
|
||||
**Map the Template's Flow**
|
||||
- Identify which tabs feed into others (e.g., Assumptions → IS → BS → CF)
|
||||
- Note any supporting schedules and their linkages to main statements
|
||||
- Document the template's specific line items and structure before populating
|
||||
|
||||
### Step 2: Filling in Data Without Breaking Formulas
|
||||
|
||||
**Golden Rules for Data Entry**
|
||||
|
||||
| Rule | Description |
|
||||
|------|-------------|
|
||||
| Only edit input cells | Never overwrite cells containing formulas unless intentionally replacing the formula |
|
||||
| Preserve cell references | When copying data, use Paste Values (Ctrl+Shift+V) to avoid overwriting formulas with source formatting |
|
||||
| Match the template's units | Verify if template uses thousands, millions, or actual values before entering data |
|
||||
| Respect sign conventions | Follow the template's existing sign convention (e.g., expenses as positive or negative) |
|
||||
| Check for circular references | If the template uses iterative calculations, ensure Enable Iterative Calculation is turned on |
|
||||
|
||||
**Safe Data Entry Process**
|
||||
1. Identify the exact cells designated for input (usually highlighted or labeled)
|
||||
2. Enter historical data first, then verify formulas are calculating correctly for those periods
|
||||
3. Enter assumption drivers that feed forecast calculations
|
||||
4. Review calculated outputs to confirm formulas are working as intended
|
||||
5. If a formula cell must be modified, document the original formula before making changes
|
||||
|
||||
**Handling Pre-Built Formulas**
|
||||
- If formulas reference cells you haven't populated yet, expect temporary errors (#REF!, #DIV/0!) until all inputs are complete
|
||||
- When formulas produce unexpected results, trace precedents to identify missing or incorrect inputs
|
||||
- Never delete rows/columns without checking for formula dependencies across all tabs
|
||||
|
||||
### Step 3: Validating Formulas
|
||||
|
||||
**Formula Integrity Checks**
|
||||
|
||||
Before relying on template outputs, validate that formulas are functioning correctly:
|
||||
|
||||
| Check Type | Method |
|
||||
|------------|--------|
|
||||
| Trace precedents | Select a formula cell → Formulas → Trace Precedents to verify it references correct inputs |
|
||||
| Trace dependents | Verify key inputs flow to expected output cells |
|
||||
| Evaluate formula | Use Formulas → Evaluate Formula to step through complex calculations |
|
||||
| Check for hardcodes | Projection formulas should reference assumptions, not contain hardcoded values |
|
||||
| Test with known values | Input simple test values to verify formulas produce expected results |
|
||||
| Cross-tab consistency | Ensure the same formula logic applies across all projection periods |
|
||||
|
||||
**Common Formula Issues to Watch For**
|
||||
- Mixed absolute/relative references causing incorrect results when copied across periods
|
||||
- Broken links to external files or deleted ranges (#REF! errors)
|
||||
- Division by zero in early periods before revenue ramps (#DIV/0! errors)
|
||||
- Circular reference warnings (may be intentional for interest calculations)
|
||||
- Inconsistent formulas across projection columns (use Ctrl+\ to find differences)
|
||||
|
||||
**Validating Cross-Tab Linkages**
|
||||
- Confirm values that appear on multiple tabs are linked (not duplicated)
|
||||
- Verify schedule totals tie to corresponding line items on main statements
|
||||
- Check that period labels align across all tabs
|
||||
|
||||
### Step 4: Quality Checks by Sheet
|
||||
|
||||
Perform these validation checks on each sheet after populating the template:
|
||||
|
||||
**Income Statement (IS) Quality Checks**
|
||||
- Revenue figures match source data for historical periods
|
||||
- All expense line items sum to reported totals
|
||||
- Subtotals (Gross Profit, EBIT, EBT, Net Income) calculate correctly
|
||||
- Tax calculation logic is appropriate (handles losses correctly)
|
||||
- Forecast drivers reference assumptions tab (no hardcodes)
|
||||
- Period-over-period changes are directionally reasonable
|
||||
|
||||
**Balance Sheet (BS) Quality Checks**
|
||||
- Assets = Liabilities + Equity for every period (primary check)
|
||||
- Cash balance matches Cash Flow Statement ending cash
|
||||
- Working capital accounts tie to supporting schedules (if applicable)
|
||||
- Retained Earnings rolls forward correctly: Prior RE + Net Income - Dividends +/- Adjustments = Ending RE
|
||||
- Debt balances tie to debt schedule (if applicable)
|
||||
- All balance sheet items have appropriate signs (assets positive, most liabilities positive)
|
||||
|
||||
**Cash Flow Statement (CF) Quality Checks**
|
||||
- Net Income at top of CFO matches Income Statement Net Income
|
||||
- Non-cash add-backs (D&A, SBC, etc.) tie to their source schedules/statements
|
||||
- Working capital changes have correct signs (increase in asset = use of cash = negative)
|
||||
- CapEx ties to PP&E schedule or fixed asset roll-forward
|
||||
- Financing activities tie to changes in debt and equity accounts on BS
|
||||
- Ending Cash matches Balance Sheet Cash
|
||||
- Beginning Cash equals prior period Ending Cash
|
||||
|
||||
**Supporting Schedule Quality Checks**
|
||||
- Opening balances equal prior period closing balances
|
||||
- Roll-forward logic is complete (Beginning + Additions - Deductions = Ending)
|
||||
- Schedule totals tie to main statement line items
|
||||
- Assumptions used in calculations match Assumptions tab
|
||||
|
||||
### Step 5: Cross-Statement Integrity Checks
|
||||
|
||||
After validating individual sheets, confirm the three statements are properly integrated:
|
||||
|
||||
| Check | Formula | Expected Result |
|
||||
|-------|---------|-----------------|
|
||||
| Balance Sheet Balance | Assets - Liabilities - Equity | = 0 |
|
||||
| Cash Tie-Out | CF Ending Cash - BS Cash | = 0 |
|
||||
| Net Income Link | IS Net Income - CF Starting Net Income | = 0 |
|
||||
| Retained Earnings | Prior RE + NI - Dividends - BS Ending RE | = 0 (adjust for SBC/other items as needed) |
|
||||
|
||||
### Step 6: Final Review
|
||||
|
||||
Before considering the model complete:
|
||||
- Toggle through all scenarios (if applicable) to verify checks pass in each case
|
||||
- Review all #REF!, #DIV/0!, #VALUE!, and #NAME? errors and resolve or document
|
||||
- Confirm all input cells have been populated (search for placeholder values)
|
||||
- Verify units are consistent across all tabs
|
||||
- Save a clean version before making any additional modifications
|
||||
|
||||
## Model Validation and Audit
|
||||
|
||||
This section consolidates all validation checks and audit procedures for completed templates.
|
||||
|
||||
### Core Linkages (Must Always Hold)
|
||||
|
||||
See [references/formulas.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/finance\3-statement-model/references/formulas.md) for all formula details.
|
||||
|
||||
| Check | Formula | Expected Result |
|
||||
|-------|---------|-----------------|
|
||||
| Balance Sheet Balance | Assets - Liabilities - Equity | = 0 |
|
||||
| Cash Tie-Out | CF Ending Cash - BS Cash | = 0 |
|
||||
| Cash Monthly vs Annual | Closing Cash (Monthly) - Closing Cash (Annual) | = 0 |
|
||||
| Net Income Link | IS Net Income - CF Starting Net Income | = 0 |
|
||||
| Retained Earnings | Prior RE + NI + SBC - Dividends - BS Ending RE | = 0 |
|
||||
| Equity Financing | ΔCommon Stock/APIC (BS) - Equity Issuance (CFF) | = 0 |
|
||||
| Year 0 Equity | Equity Raised (Year 0) - Beginning Equity Capital (Year 1) | = 0 |
|
||||
|
||||
### Sign Convention Reference
|
||||
|
||||
| Statement | Item | Sign Convention |
|
||||
|-----------|------|-----------------|
|
||||
| CFO | D&A, SBC | Positive (add-back) |
|
||||
| CFO | ΔAR (increase) | Negative (use of cash) |
|
||||
| CFO | ΔAP (increase) | Positive (source of cash) |
|
||||
| CFI | CapEx | Negative |
|
||||
| CFF | Debt issuance | Positive |
|
||||
| CFF | Debt repayments | Negative |
|
||||
| CFF | Dividends | Negative |
|
||||
|
||||
### Circular Reference Handling
|
||||
|
||||
Interest expense creates circularity: Interest → Net Income → Cash → Debt Balance → Interest
|
||||
|
||||
Enable iterative calculation in Excel: File → Options → Formulas → Enable iterative calculation. Set maximum iterations to 100, maximum change to 0.001. Add a circuit breaker toggle in Assumptions tab.
|
||||
|
||||
### Check Categories
|
||||
|
||||
**Section 1: Currency Consistency**
|
||||
- Currency identified and documented in Assumptions
|
||||
- All tabs use consistent currency symbol and scale
|
||||
- Units row matches model currency
|
||||
|
||||
**Section 2: Balance Sheet Integrity**
|
||||
- Assets = Liabilities + Equity (for each period)
|
||||
- Formula: Assets - Liabilities - Equity (must = 0)
|
||||
|
||||
**Section 3: Cash Flow Integrity**
|
||||
- Cash ties to BS (CF Ending Cash = BS Cash)
|
||||
- Cash Monthly vs Annual: Closing Cash (Monthly) = Closing Cash (Annual)
|
||||
- NI ties to IS (CF Net Income = IS Net Income)
|
||||
- D&A ties to schedule
|
||||
- SBC ties to IS
|
||||
- ΔAR, ΔInventory, ΔAP tie to WC schedule
|
||||
- CapEx ties to DA schedule
|
||||
|
||||
**Section 4: Retained Earnings**
|
||||
- RE roll-forward check: Prior RE + NI + SBC - Dividends = Ending RE
|
||||
- Show component breakdown for debugging
|
||||
|
||||
**Section 5: Working Capital**
|
||||
- AR, Inventory, AP tie to BS
|
||||
- DSO, DIO, DPO reasonability checks (flag if outside normal ranges)
|
||||
|
||||
**Section 6: Debt Schedule**
|
||||
- Total Debt ties to BS (Current + LT Debt)
|
||||
- Interest calculation ties to IS
|
||||
|
||||
**Section 6b: Equity Financing**
|
||||
- Equity issuance proceeds tie to BS Common Stock/APIC increase
|
||||
- Cash increase from equity = Equity account increase (must balance)
|
||||
- Equity Raise Tie-Out: ΔCommon Stock/APIC (BS) = Equity Issuance (CFF) (must = 0)
|
||||
- Year 0 Equity Tie-Out: Equity Raised (Year 0) = Beginning Equity Capital (Year 1)
|
||||
|
||||
**Section 6c: NOL Schedule**
|
||||
- Beginning NOL (Year 1 / Formation) = 0 (new business starts with zero NOL)
|
||||
- NOL increases only when EBT < 0 (losses must be realized to generate NOL)
|
||||
- DTA ties to BS (NOL Schedule DTA = BS Deferred Tax Asset)
|
||||
- NOL utilization ≤ 80% of EBT (post-2017 federal limitation)
|
||||
- NOL balance is non-negative (cannot utilize more than available)
|
||||
- NOL generated only when EBT < 0
|
||||
- Tax expense = 0 when taxable income ≤ 0
|
||||
|
||||
**Section 7: Scenario Hierarchy**
|
||||
- Absolute metrics: Upside > Base > Downside (NI, EBITDA, FCF)
|
||||
- Margins: Upside > Base > Downside (GM%, EBITDA%, NI%)
|
||||
- Credit metrics: Upside < Base < Downside for leverage (inverted)
|
||||
|
||||
**Section 8: Formula Integrity**
|
||||
- COGS, S&M, G&A, R&D, SBC driven by % of Revenue (no hardcodes)
|
||||
- Consistent formulas across projection years
|
||||
- No #REF!, #DIV/0!, #VALUE! errors
|
||||
|
||||
**Section 9: Credit Metric Thresholds**
|
||||
- Flag metrics as Green/Yellow/Red based on covenant thresholds
|
||||
- Summary of any red flags
|
||||
|
||||
### Master Check Formula
|
||||
|
||||
Aggregate all section statuses into a single master check:
|
||||
- If all sections pass → "✓ ALL CHECKS PASS"
|
||||
- If any section fails → "✗ ERRORS DETECTED - REVIEW BELOW"
|
||||
|
||||
### Quick Debug Workflow
|
||||
|
||||
When Master Status shows errors:
|
||||
1. Scroll to find red-highlighted sections
|
||||
2. Identify which check category has failures
|
||||
3. Navigate to source tab to investigate
|
||||
4. Fix the underlying issue
|
||||
5. Return to Checks tab to verify resolution
|
||||
|
||||
|
||||
## Data sources — MCP first, web fallback
|
||||
|
||||
Many passages below say "use the S&P Kensho MCP / Daloopa MCP / FactSet MCP". Those are commercial financial-data MCPs from the original Cowork plugin context. In Hermes:
|
||||
|
||||
- **If you have any structured financial-data MCP configured** (Hermes supports MCP — see `native-mcp` skill), prefer it for point-in-time comps, precedent transactions, and filings.
|
||||
- **Otherwise**, fall back to:
|
||||
- `web_search` / `web_extract` against SEC EDGAR (`https://www.sec.gov/cgi-bin/browse-edgar`) for US filings
|
||||
- Company IR pages for press releases, earnings decks
|
||||
- `browser_navigate` for interactive data portals
|
||||
- User-provided data (explicitly ask when the context doesn't have it)
|
||||
- **Never fabricate**. If a multiple, precedent, or filing number can't be sourced, flag the cell as `[UNSOURCED]` and surface it to the user.
|
||||
|
||||
## Attribution
|
||||
|
||||
This skill is adapted from Anthropic's Claude for Financial Services plugin suite (Apache-2.0). The Office-JS / Cowork live-Excel paths have been removed; this version targets headless openpyxl via the `excel-author` skill's conventions. Original: https://github.com/anthropics/financial-services
|
||||
@@ -0,0 +1,682 @@
|
||||
---
|
||||
title: "Comps Analysis — Build comparable-company valuation workbooks in Excel"
|
||||
sidebar_label: "Comps Analysis"
|
||||
description: "Build comparable-company valuation workbooks in Excel"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Comps Analysis
|
||||
|
||||
Build comparable-company valuation workbooks in Excel.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/finance/comps-analysis` |
|
||||
| Path | `optional-skills/finance\comps-analysis` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Anthropic (adapted by Nous Research) |
|
||||
| License | Apache-2.0 |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `finance`, `valuation`, `comps`, `excel`, `openpyxl`, `modeling`, `investment-banking` |
|
||||
| Related skills | [`excel-author`](/docs/user-guide/skills/optional/finance/finance-excel-author), [`pptx-author`](/docs/user-guide/skills/optional/finance/finance-pptx-author), [`dcf-model`](/docs/user-guide/skills/optional/finance/finance-dcf-model), [`lbo-model`](/docs/user-guide/skills/optional/finance/finance-lbo-model) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
## Environment
|
||||
|
||||
This skill assumes **headless openpyxl** — you are producing an .xlsx file on disk.
|
||||
Follow the `excel-author` skill's conventions for cell coloring, formulas, named ranges, and sensitivity tables.
|
||||
Recalculate before delivery: `python /path/to/excel-author/scripts/recalc.py ./out/model.xlsx`.
|
||||
|
||||
# Comparable Company Analysis
|
||||
|
||||
## ⚠️ CRITICAL: Data Source Priority (READ FIRST)
|
||||
|
||||
**ALWAYS follow this data source hierarchy:**
|
||||
|
||||
1. **FIRST: Check for MCP data sources** - If S&P Kensho MCP, FactSet MCP, or Daloopa MCP are available, use them exclusively for financial and trading information
|
||||
2. **DO NOT use web search** if the above MCP data sources are available
|
||||
3. **ONLY if MCPs are unavailable:** Then use Bloomberg Terminal, SEC EDGAR filings, or other institutional sources
|
||||
4. **NEVER use web search as a primary data source** - it lacks the accuracy, audit trails, and reliability required for institutional-grade analysis
|
||||
|
||||
**Why this matters:** MCP sources provide verified, institutional-grade data with proper citations. Web search results can be outdated, inaccurate, or unreliable for financial analysis.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
This skill teaches the agent to build institutional-grade comparable company analyses that combine operating metrics, valuation multiples, and statistical benchmarking. The output is a structured Excel/spreadsheet that enables informed investment decisions through peer comparison.
|
||||
|
||||
**Reference Material & Contextualization:**
|
||||
|
||||
An example comparable company analysis is provided in `examples/comps_example.xlsx`. When using this or other example files in this skill directory, use them intelligently:
|
||||
|
||||
**DO use examples for:**
|
||||
- Understanding structural hierarchy (how sections flow)
|
||||
- Grasping the level of rigor expected (statistical depth, documentation standards)
|
||||
- Learning principles (clear headers, transparent formulas, audit trails)
|
||||
|
||||
**DO NOT use examples for:**
|
||||
- Exact reproduction of format or metrics
|
||||
- Copying layout without considering context
|
||||
- Applying the same visual style regardless of audience
|
||||
|
||||
**ALWAYS ask yourself first:**
|
||||
1. **"Do you have a preferred format or should I adapt the template style?"**
|
||||
2. **"Who is the audience?"** (Investment committee, board presentation, quick reference, detailed memo)
|
||||
3. **"What's the key question?"** (Valuation, growth analysis, competitive positioning, efficiency)
|
||||
4. **"What's the context?"** (M&A evaluation, investment decision, sector benchmarking, performance review)
|
||||
|
||||
**Adapt based on specifics:**
|
||||
- **Industry context**: Big tech mega-caps need different metrics than emerging SaaS startups
|
||||
- **Sector-specific needs**: Add relevant metrics early (e.g., cloud ARR, enterprise customers, developer ecosystem for tech)
|
||||
- **Company familiarity**: Well-known companies may need less background, more focus on delta analysis
|
||||
- **Decision type**: M&A requires different emphasis than ongoing portfolio monitoring
|
||||
|
||||
**Core principle:** Use template principles (clear structure, statistical rigor, transparent formulas) but vary execution based on context. The goal is institutional-quality analysis, not institutional-looking templates.
|
||||
|
||||
User-provided examples and explicit preferences always take precedence over defaults.
|
||||
|
||||
## Core Philosophy
|
||||
**"Build the right structure first, then let the data tell the story."**
|
||||
|
||||
Start with headers that force strategic thinking about what matters, input clean data, build transparent formulas, and let statistics emerge automatically. A good comp should be immediately readable by someone who didn't build it.
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ CRITICAL: Formulas Over Hardcodes + Step-by-Step Verification
|
||||
|
||||
**Formulas, not hardcodes:**
|
||||
- Every derived value (margin, multiple, statistic) MUST be an Excel formula referencing input cells — never a pre-computed number pasted in
|
||||
- When using Python/openpyxl to build the sheet: write `cell.value = "=E7/C7"` (formula string), NOT `cell.value = 0.687` (computed result)
|
||||
- The only hardcoded values should be raw input data (revenue, EBITDA, share price, etc.) — and every one of those gets a cell comment with its source
|
||||
- Why: the model must update automatically when an input changes. A hardcoded margin is a silent bug waiting to happen.
|
||||
|
||||
**Verify step-by-step with the user:**
|
||||
- After setting up the structure → show the user the header layout before filling data
|
||||
- After entering raw inputs → show the user the input block and confirm sources/periods before building formulas
|
||||
- After building operating metrics formulas → show the calculated margins and sanity-check with the user before moving to valuation
|
||||
- After building valuation multiples → show the multiples and confirm they look reasonable before adding statistics
|
||||
- Do NOT build the entire sheet end-to-end and then present it — catch errors early by confirming each section
|
||||
|
||||
---
|
||||
|
||||
## Section 1: Document Structure & Setup
|
||||
|
||||
### Header Block (Rows 1-3)
|
||||
```
|
||||
Row 1: [ANALYSIS TITLE] - COMPARABLE COMPANY ANALYSIS
|
||||
Row 2: [List of Companies with Tickers] • [Company 1 (TICK1)] • [Company 2 (TICK2)] • [Company 3 (TICK3)]
|
||||
Row 3: As of [Period] | All figures in [USD Millions/Billions] except per-share amounts and ratios
|
||||
```
|
||||
|
||||
**Why this matters:** Establishes context immediately. Anyone opening this file knows what they're looking at, when it was created, and how to interpret the numbers.
|
||||
|
||||
### Visual Convention Standards (OPTIONAL - User preferences and uploaded templates always override)
|
||||
|
||||
**IMPORTANT: These are suggested defaults only. Always prioritize:**
|
||||
1. User's explicit formatting preferences
|
||||
2. Formatting from any uploaded template files
|
||||
3. Company/team style guides
|
||||
4. These defaults (only if no other guidance provided)
|
||||
|
||||
**Suggested Font & Typography:**
|
||||
- **Font family**: Times New Roman (professional, readable, industry standard)
|
||||
- **Font size**: 11pt for data cells, 12pt for headers
|
||||
- **Bold text**: Section headers, company names, statistic labels
|
||||
|
||||
**Default Color & Shading — Professional Blue/Grey Palette (minimal is better):**
|
||||
- **Keep it restrained** — only blues and greys. Do NOT introduce greens, oranges, reds, or multiple accent colors. A clean comps sheet uses 3-4 colors total.
|
||||
- **Section headers** (e.g., "OPERATING STATISTICS & FINANCIAL METRICS"):
|
||||
- Dark blue background (`#1F4E79` or `#17365D` navy)
|
||||
- White bold text
|
||||
- Full row shading across all columns
|
||||
- **Column headers** (e.g., "Company", "Revenue", "Margin"):
|
||||
- Light blue background (`#D9E1F2` or similar pale blue)
|
||||
- Black bold text
|
||||
- Centered alignment
|
||||
- **Data rows**:
|
||||
- White background for company data
|
||||
- Black text for formulas; blue text for hardcoded inputs
|
||||
- **Statistics rows** (Maximum, 75th Percentile, etc.):
|
||||
- Light grey background (`#F2F2F2`)
|
||||
- Black text, left-aligned labels
|
||||
- **That's the whole palette**: dark blue + light blue + light grey + white. Nothing else unless the user's template says otherwise.
|
||||
|
||||
**Suggested Formatting Conventions:**
|
||||
- **Decimal precision**:
|
||||
- Percentages: 1 decimal (12.3%)
|
||||
- Multiples: 1 decimal (13.5x)
|
||||
- Dollar amounts: No decimals, thousands separator (69,632)
|
||||
- Margins shown as percentages: 1 decimal (68.7%)
|
||||
- **Borders**: No borders (clean, minimal appearance)
|
||||
- **Alignment**: All metrics center-aligned for clean, uniform appearance
|
||||
- **Cell dimensions**: All column widths should be uniform/even, all row heights should be consistent (creates clean, professional grid)
|
||||
|
||||
**Note:** If the user provides a template file or specifies different formatting, use that instead.
|
||||
|
||||
---
|
||||
|
||||
## Section 2: Operating Statistics & Financial Metrics
|
||||
|
||||
### Core Columns (Start with these)
|
||||
1. **Company** - Names with consistent formatting
|
||||
2. **Revenue** - Size metric (can be LTM, quarterly, or annual depending on context)
|
||||
3. **Revenue Growth** - Year-over-year percentage change
|
||||
4. **Gross Profit** - Revenue minus cost of goods sold
|
||||
5. **Gross Margin** - GP/Revenue (fundamental profitability)
|
||||
6. **EBITDA** - Earnings before interest, tax, depreciation, amortization
|
||||
7. **EBITDA Margin** - EBITDA/Revenue (operating efficiency)
|
||||
|
||||
### Optional Additions (Choose based on industry/purpose)
|
||||
- **Quarterly vs LTM** - Include both if seasonality matters
|
||||
- **Free Cash Flow** - For capital-intensive or SaaS businesses
|
||||
- **FCF Margin** - FCF/Revenue (cash generation efficiency)
|
||||
- **Net Income** - For mature, profitable companies
|
||||
- **Operating Income** - For businesses with varying D&A
|
||||
- **CapEx metrics** - For asset-heavy industries
|
||||
- **Rule of 40** - Specifically for SaaS (Growth % + Margin %)
|
||||
- **FCF Conversion** - For quality of earnings analysis (advanced)
|
||||
|
||||
### Formula Examples (Using Row 7 as example)
|
||||
```excel
|
||||
// Core ratios - these are always calculated
|
||||
Gross Margin (F7): =E7/C7
|
||||
EBITDA Margin (H7): =G7/C7
|
||||
|
||||
// Optional ratios - include if relevant
|
||||
FCF Margin: =[FCF]/[Revenue]
|
||||
Net Margin: =[Net Income]/[Revenue]
|
||||
Rule of 40: =[Growth %]+[FCF Margin %]
|
||||
```
|
||||
|
||||
**Golden Rule:** Every ratio should be [Something] / [Revenue] or [Something] / [Something from this sheet]. Keep it simple.
|
||||
|
||||
### Statistics Block (After company data)
|
||||
|
||||
**CRITICAL: Add statistics formulas for all comparable metrics (ratios, margins, growth rates, multiples).**
|
||||
|
||||
```
|
||||
[Leave one blank row for visual separation]
|
||||
- Maximum: =MAX(B7:B9)
|
||||
- 75th Percentile: =QUARTILE(B7:B9,3)
|
||||
- Median: =MEDIAN(B7:B9)
|
||||
- 25th Percentile: =QUARTILE(B7:B9,1)
|
||||
- Minimum: =MIN(B7:B9)
|
||||
```
|
||||
|
||||
**Columns that NEED statistics (comparable metrics):**
|
||||
- Revenue Growth %, Gross Margin %, EBITDA Margin %, EPS
|
||||
- EV/Revenue, EV/EBITDA, P/E, Dividend Yield %, Beta
|
||||
|
||||
**Columns that DON'T need statistics (size metrics):**
|
||||
- Revenue, EBITDA, Net Income (absolute size varies by company scale)
|
||||
- Market Cap, Enterprise Value (not comparable across different-sized companies)
|
||||
|
||||
**Note:** Add one blank row between company data and statistics rows for visual separation. Do NOT add a "SECTOR STATISTICS" or "VALUATION STATISTICS" header row.
|
||||
|
||||
**Why quartiles matter:** They show distribution, not just average. A 75th percentile multiple tells you what "premium" companies trade at.
|
||||
|
||||
---
|
||||
|
||||
## Section 3: Valuation Multiples & Investment Metrics
|
||||
|
||||
### Core Valuation Columns (Start with these)
|
||||
1. **Company** - Same order as operating section
|
||||
2. **Market Cap** - Current market valuation
|
||||
3. **Enterprise Value** - Market Cap ± Net Debt/Cash
|
||||
4. **EV/Revenue** - How much market pays per dollar of sales
|
||||
5. **EV/EBITDA** - How much market pays per dollar of earnings
|
||||
6. **P/E Ratio** - Price relative to net earnings
|
||||
|
||||
### Optional Valuation Metrics (Choose based on context)
|
||||
- **FCF Yield** - FCF/Market Cap (for cash-focused analysis)
|
||||
- **PEG Ratio** - P/E/Growth Rate (for growth companies)
|
||||
- **Price/Book** - Market value vs. book value (for asset-heavy businesses)
|
||||
- **ROE/ROA** - Return metrics (for profitability comparison)
|
||||
- **Revenue/EBITDA CAGR** - Historical growth rates (for trend analysis)
|
||||
- **Asset Turnover** - Revenue/Assets (for operational efficiency)
|
||||
- **Debt/Equity** - Leverage (for capital structure analysis)
|
||||
|
||||
**Key Principle:** Include 3-5 core multiples that matter for your industry. Don't include every possible metric just because you can.
|
||||
|
||||
### Formula Examples
|
||||
```excel
|
||||
// Core multiples - always include these
|
||||
EV/Revenue: =[Enterprise Value]/[LTM Revenue]
|
||||
EV/EBITDA: =[Enterprise Value]/[LTM EBITDA]
|
||||
P/E Ratio: =[Market Cap]/[Net Income]
|
||||
|
||||
// Optional multiples - include if data available
|
||||
FCF Yield: =[LTM FCF]/[Market Cap]
|
||||
PEG Ratio: =[P/E]/[Growth Rate %]
|
||||
```
|
||||
|
||||
### Cross-Reference Rule
|
||||
**CRITICAL:** Valuation multiples MUST reference the operating metrics section. Never input the same raw data twice. If revenue is in C7, then EV/Revenue formula should reference C7.
|
||||
|
||||
### Statistics Block
|
||||
Same structure as operating section: Max, 75th, Median, 25th, Min for every metric. Add one blank row for visual separation between company data and statistics. Do NOT add a "VALUATION STATISTICS" header row.
|
||||
|
||||
---
|
||||
|
||||
## Section 4: Notes & Methodology Documentation
|
||||
|
||||
### Required Components
|
||||
|
||||
**Data Sources & Quality:**
|
||||
- Where did the data come from? (S&P Kensho MCP, FactSet MCP, Daloopa MCP, Bloomberg, SEC filings)
|
||||
- What period does it cover? (Q4 2024, audited figures)
|
||||
- How was it verified? (Cross-checked against 10-K/10-Q)
|
||||
- Note: Prioritize MCP data sources (S&P Kensho, FactSet, Daloopa) if available for better accuracy and traceability
|
||||
|
||||
**Key Definitions:**
|
||||
- EBITDA calculation method (Gross Profit + D&A, or Operating Income + D&A)
|
||||
- Free Cash Flow formula (Operating CF - CapEx)
|
||||
- Special metrics explained (Rule of 40, FCF Conversion)
|
||||
- Time period definitions (LTM, CAGR calculation periods)
|
||||
|
||||
**Valuation Methodology:**
|
||||
- How was Enterprise Value calculated? (Market Cap + Net Debt)
|
||||
- What growth rates were used? (Historical CAGR, forward estimates)
|
||||
- Any adjustments made? (One-time items excluded, normalized margins)
|
||||
|
||||
**Analysis Framework:**
|
||||
- What's the investment thesis? (Cloud/SaaS efficiency)
|
||||
- What metrics matter most? (Cash generation, capital efficiency)
|
||||
- How should readers interpret the statistics? (Quartiles provide context)
|
||||
|
||||
---
|
||||
|
||||
## Section 5: Choosing the Right Metrics (Decision Framework)
|
||||
|
||||
### Start with "What question am I answering?"
|
||||
|
||||
**"Which company is undervalued?"**
|
||||
→ Focus on: EV/Revenue, EV/EBITDA, P/E, Market Cap
|
||||
→ Skip: Operational details, growth metrics
|
||||
|
||||
**"Which company is most efficient?"**
|
||||
→ Focus on: Gross Margin, EBITDA Margin, FCF Margin, Asset Turnover
|
||||
→ Skip: Size metrics, absolute dollar amounts
|
||||
|
||||
**"Which company is growing fastest?"**
|
||||
→ Focus on: Revenue Growth %, EBITDA CAGR, User/Customer Growth
|
||||
→ Skip: Margin metrics, leverage ratios
|
||||
|
||||
**"Which is the best cash generator?"**
|
||||
→ Focus on: FCF, FCF Margin, FCF Conversion, CapEx intensity
|
||||
→ Skip: EBITDA, P/E ratios
|
||||
|
||||
### Industry-Specific Metric Selection
|
||||
|
||||
**Software/SaaS:**
|
||||
Must have: Revenue Growth, Gross Margin, Rule of 40
|
||||
Optional: ARR, Net Dollar Retention, CAC Payback
|
||||
Skip: Asset Turnover, Inventory metrics
|
||||
|
||||
**Manufacturing/Industrials:**
|
||||
Must have: EBITDA Margin, Asset Turnover, CapEx/Revenue
|
||||
Optional: ROA, Inventory Turns, Backlog
|
||||
Skip: Rule of 40, SaaS metrics
|
||||
|
||||
**Financial Services:**
|
||||
Must have: ROE, ROA, Efficiency Ratio, P/E
|
||||
Optional: Net Interest Margin, Loan Loss Reserves
|
||||
Skip: Gross Margin, EBITDA (not meaningful for banks)
|
||||
|
||||
**Retail/E-commerce:**
|
||||
Must have: Revenue Growth, Gross Margin, Inventory Turnover
|
||||
Optional: Same-Store Sales, Customer Acquisition Cost
|
||||
Skip: Heavy R&D or CapEx metrics
|
||||
|
||||
### The "5-10 Rule"
|
||||
|
||||
**5 operating metrics** - Revenue, Growth, 2-3 margins/efficiency metrics
|
||||
**5 valuation metrics** - Market Cap, EV, 3 multiples
|
||||
**= 10 total columns** - Enough to tell the story, not so many you lose the thread
|
||||
|
||||
If you have more than 15 metrics, you're probably including noise. Edit ruthlessly.
|
||||
|
||||
---
|
||||
|
||||
## Section 6: Best Practices & Quality Checks
|
||||
|
||||
### Before You Start
|
||||
1. **Define the peer group** - Companies must be truly comparable (similar business model, scale, geography)
|
||||
2. **Choose the right period** - LTM smooths seasonality; quarterly shows trends
|
||||
3. **Standardize units upfront** - Millions vs. billions decision affects everything
|
||||
4. **Map data sources** - Know where each number comes from
|
||||
|
||||
### As You Build
|
||||
1. **Input all raw data first** - Complete the blue text before writing formulas
|
||||
2. **Add cell comments to ALL hard-coded inputs** - Right-click cell → Insert Comment → Document source OR assumption
|
||||
|
||||
**For sourced data, cite exactly where it came from:**
|
||||
- Example: "Bloomberg Terminal - MSFT Equity DES, accessed 2024-10-02"
|
||||
- Example: "Q4 2024 10-K filing, page 42, line item 'Total Revenue'"
|
||||
- Example: "FactSet consensus estimate as of 2024-10-02"
|
||||
- **Include hyperlinks when possible**: Right-click cell → Link → paste URL to SEC filing, data source, or report
|
||||
|
||||
**For assumptions, explain the reasoning:**
|
||||
- Example: "Assumed 15% EBITDA margin based on peer median, company does not disclose"
|
||||
- Example: "Estimated Enterprise Value as Market Cap + $50M net debt (from Q3 balance sheet, Q4 not yet available)"
|
||||
- Example: "Forward P/E based on street consensus EPS of $3.45 (average of 12 analyst estimates)"
|
||||
|
||||
**Why this matters**: Enables audit trails, data verification, assumption transparency, and future updates
|
||||
3. **Build formulas row by row** - Test each calculation before moving on
|
||||
4. **Use absolute references for headers** - $C$6 locks the header row
|
||||
5. **Format consistently** - Percentages as percentages, not decimals
|
||||
6. **Add conditional formatting** - Highlight outliers automatically
|
||||
|
||||
### Sanity Checks
|
||||
- **Margin test**: Gross margin > EBITDA margin > Net margin (always true by definition)
|
||||
- **Multiple reasonableness**:
|
||||
- EV/Revenue: typically 0.5-20x (varies widely by industry)
|
||||
- EV/EBITDA: typically 8-25x (fairly consistent across industries)
|
||||
- P/E: typically 10-50x (depends on growth rate)
|
||||
- **Growth-multiple correlation**: Higher growth usually means higher multiples
|
||||
- **Size-efficiency trade-off**: Larger companies often have better margins (scale benefits)
|
||||
|
||||
### Common Mistakes to Avoid
|
||||
❌ Mixing market cap and enterprise value in formulas
|
||||
❌ Using different time periods for numerator and denominator (LTM vs quarterly)
|
||||
❌ Hardcoding numbers into formulas instead of cell references
|
||||
❌ **Hard-coded inputs without cell comments citing the source OR explaining the assumption**
|
||||
❌ Missing hyperlinks to SEC filings or data sources when available
|
||||
❌ Including too many metrics without clear purpose
|
||||
❌ Including non-comparable companies (different business models)
|
||||
❌ Using outdated data without disclosure
|
||||
❌ Calculating averages of percentages incorrectly (should be median)
|
||||
|
||||
---
|
||||
|
||||
## Section 6: Advanced Features
|
||||
|
||||
### Dynamic Headers
|
||||
For columns showing calculations, use clear unit labels:
|
||||
```
|
||||
Revenue Growth (YoY) % | EBITDA Margin | FCF Margin | Rule of 40
|
||||
```
|
||||
|
||||
### Quartile Analysis Benefits
|
||||
Instead of just mean/median, quartiles show:
|
||||
- **75th percentile** = "Premium" companies trade here
|
||||
- **Median** = Typical market valuation
|
||||
- **25th percentile** = "Discount" territory
|
||||
|
||||
This helps answer: "Is our target company trading rich or cheap vs. peers?"
|
||||
|
||||
### Industry-Specific Modifications
|
||||
|
||||
**Software/SaaS:**
|
||||
- Add: ARR, Net Dollar Retention, CAC Payback Period
|
||||
- Emphasize: Rule of 40, FCF margins, gross margins >70%
|
||||
|
||||
**Healthcare:**
|
||||
- Add: R&D/Revenue, Pipeline value, Regulatory status
|
||||
- Emphasize: EBITDA margins, growth rates, reimbursement risk
|
||||
|
||||
**Industrials:**
|
||||
- Add: Backlog, Order book trends, Geographic mix
|
||||
- Emphasize: ROIC, asset turnover, cyclical adjustments
|
||||
|
||||
**Consumer:**
|
||||
- Add: Same-store sales, Customer acquisition cost, Brand value
|
||||
- Emphasize: Revenue growth, gross margins, inventory turns
|
||||
|
||||
---
|
||||
|
||||
## Section 7: Workflow & Practical Tips
|
||||
|
||||
### Step-by-Step Process
|
||||
1. **Set up structure** (30 minutes)
|
||||
- Create all headers
|
||||
- Format cells (blue for inputs, black for formulas)
|
||||
- Lock in units and date references
|
||||
|
||||
2. **Gather data** (60-90 minutes)
|
||||
- Pull from primary sources (S&P Kensho MCP, FactSet MCP, Daloopa MCP if available; otherwise Bloomberg, SEC)
|
||||
- Input all raw numbers in blue
|
||||
- Document sources in notes section
|
||||
|
||||
3. **Build formulas** (30 minutes)
|
||||
- Start with simple ratios (margins)
|
||||
- Progress to multiples (EV/Revenue)
|
||||
- Add cross-checks (do margins make sense?)
|
||||
|
||||
4. **Add statistics** (15 minutes)
|
||||
- Copy formula structure for all columns
|
||||
- Verify ranges are correct (B7:B9, not B7:B10)
|
||||
- Check quartile logic
|
||||
|
||||
5. **Quality control** (30 minutes)
|
||||
- Run sanity checks
|
||||
- Verify formula references
|
||||
- Check for #DIV/0! or #REF! errors
|
||||
- Compare against known benchmarks
|
||||
|
||||
6. **Documentation** (15 minutes)
|
||||
- Complete notes section
|
||||
- Add data sources
|
||||
- Define methodologies
|
||||
- Date-stamp the analysis
|
||||
|
||||
### Pro Tips
|
||||
- **Save templates**: Build once, reuse forever
|
||||
- **Color-code outliers**: Conditional formatting for values >2 standard deviations
|
||||
- **Link to source files**: Hyperlink to Bloomberg screenshots or SEC filings
|
||||
- **Version control**: Save as "Comps_v1_2024-12-15" with clear dating
|
||||
- **Collaborative reviews**: Have someone else check your formulas
|
||||
|
||||
### Excel Formatting Checklist (Optional - adapt to user preferences)
|
||||
- [ ] Font set to user's preferred style (default: Times New Roman, 11pt data, 12pt headers)
|
||||
- [ ] Section headers formatted per user's template (default: dark blue #17365D with white bold text)
|
||||
- [ ] Column headers formatted per user's template (default: light blue/gray #D9E2F3 with black bold text)
|
||||
- [ ] Statistics rows formatted per user's template (default: light gray #F2F2F2)
|
||||
- [ ] No borders applied (clean, minimal appearance)
|
||||
- [ ] **Column widths set to uniform/even width** (creates clean, professional appearance)
|
||||
- [ ] **Row heights set to consistent height** (typically 20-25pt for data rows)
|
||||
- [ ] Numbers formatted with proper decimal precision and thousands separators
|
||||
- [ ] **All metrics center-aligned** for clean, uniform appearance
|
||||
- [ ] **One blank row for separation between company data and statistics rows**
|
||||
- [ ] **No separate "SECTOR STATISTICS" or "VALUATION STATISTICS" header rows**
|
||||
- [ ] **Every hard-coded input cell has a comment with either: (1) exact data source, OR (2) assumption explanation**
|
||||
- [ ] **Hyperlinks added to cells where applicable** (SEC filings, data provider pages, reports)
|
||||
|
||||
---
|
||||
|
||||
## Section 8: Example Template Layout
|
||||
|
||||
**Simple Version (Start here):**
|
||||
<!-- ascii-guard-ignore -->
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ TECHNOLOGY - COMPARABLE COMPANY ANALYSIS │
|
||||
│ Microsoft • Alphabet • Amazon │
|
||||
│ As of Q4 2024 | All figures in USD Millions │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ OPERATING METRICS │
|
||||
├──────────┬─────────┬─────────┬──────────┬──────────────────┤
|
||||
│ Company │ Revenue │ Growth │ Gross │ EBITDA │ EBITDA │
|
||||
│ │ (LTM) │ (YoY) │ Margin │ (LTM) │ Margin │
|
||||
├──────────┼─────────┼─────────┼──────────┼─────────┼────────┤
|
||||
│ MSFT │ 261,400 │ 12.3% │ 68.7% │ 205,100 │ 78.4% │
|
||||
│ GOOGL │ 349,800 │ 11.8% │ 57.9% │ 239,300 │ 68.4% │
|
||||
│ AMZN │ 638,100 │ 10.5% │ 47.3% │ 152,600 │ 23.9% │
|
||||
│ │ │ │ │ │ │ [blank row]
|
||||
│ Median │ =MEDIAN │ =MEDIAN │ =MEDIAN │ =MEDIAN │=MEDIAN │
|
||||
│ 75th % │ =QUART │ =QUART │ =QUART │ =QUART │=QUART │
|
||||
│ 25th % │ =QUART │ =QUART │ =QUART │ =QUART │=QUART │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ VALUATION MULTIPLES │
|
||||
├──────────┬──────────┬──────────┬──────────┬────────────────┤
|
||||
│ Company │ Mkt Cap │ EV │ EV/Rev │ EV/EBITDA │ P/E│
|
||||
├──────────┼──────────┼──────────┼──────────┼───────────┼────┤
|
||||
│ MSFT │3,550,000 │3,530,000 │ 13.5x │ 17.2x │36.0│
|
||||
│ GOOGL │2,030,000 │1,960,000 │ 5.6x │ 8.2x │24.5│
|
||||
│ AMZN │2,226,000 │2,320,000 │ 3.6x │ 15.2x │58.3│
|
||||
│ │ │ │ │ │ │ [blank row]
|
||||
│ Median │ =MEDIAN │ =MEDIAN │ =MEDIAN │ =MEDIAN │=MED│
|
||||
│ 75th % │ =QUART │ =QUART │ =QUART │ =QUART │=QRT│
|
||||
│ 25th % │ =QUART │ =QUART │ =QUART │ =QUART │=QRT│
|
||||
└──────────┴──────────┴──────────┴──────────┴───────────┴────┘
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
**Add complexity only when needed:**
|
||||
- Include quarterly AND LTM if seasonality matters
|
||||
- Add FCF metrics if cash generation is key story
|
||||
- Include industry-specific metrics (Rule of 40 for SaaS, etc.)
|
||||
- Add more statistics rows if you have >5 companies
|
||||
|
||||
---
|
||||
|
||||
## Section 9: Industry-Specific Additions (Optional)
|
||||
|
||||
Only add these if they're critical to your analysis. Most comps work fine with just core metrics.
|
||||
|
||||
**Software/SaaS:**
|
||||
Add if relevant: ARR, Net Dollar Retention, Rule of 40
|
||||
|
||||
**Financial Services:**
|
||||
Add if relevant: ROE, Net Interest Margin, Efficiency Ratio
|
||||
|
||||
**E-commerce:**
|
||||
Add if relevant: GMV, Take Rate, Active Buyers
|
||||
|
||||
**Healthcare:**
|
||||
Add if relevant: R&D/Revenue, Pipeline Value, Patent Timeline
|
||||
|
||||
**Manufacturing:**
|
||||
Add if relevant: Asset Turnover, Inventory Turns, Backlog
|
||||
|
||||
---
|
||||
|
||||
## Section 10: Red Flags & Warning Signs
|
||||
|
||||
### Data Quality Issues
|
||||
🚩 Inconsistent time periods (mixing quarterly and annual)
|
||||
🚩 Missing data without explanation
|
||||
🚩 Significant differences between data sources (>10% variance)
|
||||
|
||||
### Valuation Red Flags
|
||||
🚩 Negative EBITDA companies being valued on EBITDA multiples (use revenue multiples instead)
|
||||
🚩 P/E ratios >100x without hypergrowth story
|
||||
🚩 Margins that don't make sense for the industry
|
||||
|
||||
### Comparability Issues
|
||||
🚩 Different fiscal year ends (causes timing problems)
|
||||
🚩ixing pure-play and conglomerates
|
||||
🚩 Materially different business models labeled as "comps"
|
||||
|
||||
**When in doubt, exclude the company.** Better to have 3 perfect comps than 6 questionable ones.
|
||||
|
||||
---
|
||||
|
||||
## Section 11: Formulas Reference Guide
|
||||
|
||||
### Essential Excel Formulas
|
||||
```excel
|
||||
// Statistical Functions
|
||||
=AVERAGE(range) // Simple mean
|
||||
=MEDIAN(range) // Middle value
|
||||
=QUARTILE(range, 1) // 25th percentile
|
||||
=QUARTILE(range, 3) // 75th percentile
|
||||
=MAX(range) // Maximum value
|
||||
=MIN(range) // Minimum value
|
||||
=STDEV.P(range) // Standard deviation
|
||||
|
||||
// Financial Calculations
|
||||
=B7/C7 // Simple ratio (Margin)
|
||||
=SUM(B7:B9)/3 // Average of multiple companies
|
||||
=IF(B7>0, C7/B7, "N/A") // Conditional calculation
|
||||
=IFERROR(C7/D7, 0) // Handle divide by zero
|
||||
|
||||
// Cross-Sheet References
|
||||
='Sheet1'!B7 // Reference another sheet
|
||||
=VLOOKUP(A7, Table1, 2) // Lookup from data table
|
||||
=INDEX(MATCH()) // Advanced lookup
|
||||
|
||||
// Formatting
|
||||
=TEXT(B7, "0.0%") // Format as percentage
|
||||
=TEXT(C7, "#,##0") // Thousands separator
|
||||
```
|
||||
|
||||
### Common Ratio Formulas
|
||||
```excel
|
||||
Gross Margin = Gross Profit / Revenue
|
||||
EBITDA Margin = EBITDA / Revenue
|
||||
FCF Margin = Free Cash Flow / Revenue
|
||||
FCF Conversion = FCF / Operating Cash Flow
|
||||
ROE = Net Income / Shareholders' Equity
|
||||
ROA = Net Income / Total Assets
|
||||
Asset Turnover = Revenue / Total Assets
|
||||
Debt/Equity = Total Debt / Shareholders' Equity
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Key Principles Summary
|
||||
|
||||
1. **Structure drives insight** - Right headers force right thinking
|
||||
2. **Less is more** - 5-10 metrics that matter beat 20 that don't
|
||||
3. **Choose metrics for your question** - Valuation analysis ≠ efficiency analysis
|
||||
4. **Statistics show patterns** - Median/quartiles reveal more than average
|
||||
5. **Transparency beats complexity** - Simple formulas everyone understands
|
||||
6. **Comparability is king** - Better to exclude than force a bad comp
|
||||
7. **Document your choices** - Explain which metrics and why in notes section
|
||||
|
||||
---
|
||||
|
||||
## Output Checklist
|
||||
|
||||
Before delivering a comp analysis, verify:
|
||||
- [ ] All companies are truly comparable
|
||||
- [ ] Data is from consistent time periods
|
||||
- [ ] Units are clearly labeled (millions/billions)
|
||||
- [ ] Formulas reference cells, not hardcoded values
|
||||
- [ ] **All hard-coded input cells have comments with either: (1) exact data source with citation, OR (2) clear assumption with explanation**
|
||||
- [ ] **Hyperlinks added where relevant** (SEC EDGAR filings, Bloomberg pages, research reports)
|
||||
- [ ] Statistics include at least 5 metrics (Max, 75th, Med, 25th, Min)
|
||||
- [ ] Notes section documents sources and methodology
|
||||
- [ ] Visual formatting follows conventions (blue = input, black = formula)
|
||||
- [ ] Sanity checks pass (margins logical, multiples reasonable)
|
||||
- [ ] Date stamp is current ("As of [Date]")
|
||||
- [ ] Formula auditing shows no errors (#DIV/0!, #REF!, #N/A)
|
||||
|
||||
---
|
||||
|
||||
## Continuous Improvement
|
||||
|
||||
After completing a comp analysis, ask:
|
||||
1. Did the statistics reveal unexpected insights?
|
||||
2. Were there any data gaps that limited analysis?
|
||||
3. Did stakeholders ask for metrics you didn't include?
|
||||
4. How long did it take vs. how long should it take?
|
||||
5. What would make this more useful next time?
|
||||
|
||||
The best comp analyses evolve with each iteration. Save templates, learn from feedback, and refine the structure based on what decision-makers actually use.
|
||||
|
||||
|
||||
## Data sources — MCP first, web fallback
|
||||
|
||||
Many passages below say "use the S&P Kensho MCP / Daloopa MCP / FactSet MCP". Those are commercial financial-data MCPs from the original Cowork plugin context. In Hermes:
|
||||
|
||||
- **If you have any structured financial-data MCP configured** (Hermes supports MCP — see `native-mcp` skill), prefer it for point-in-time comps, precedent transactions, and filings.
|
||||
- **Otherwise**, fall back to:
|
||||
- `web_search` / `web_extract` against SEC EDGAR (`https://www.sec.gov/cgi-bin/browse-edgar`) for US filings
|
||||
- Company IR pages for press releases, earnings decks
|
||||
- `browser_navigate` for interactive data portals
|
||||
- User-provided data (explicitly ask when the context doesn't have it)
|
||||
- **Never fabricate**. If a multiple, precedent, or filing number can't be sourced, flag the cell as `[UNSOURCED]` and surface it to the user.
|
||||
|
||||
## Attribution
|
||||
|
||||
This skill is adapted from Anthropic's Claude for Financial Services plugin suite (Apache-2.0). The Office-JS / Cowork live-Excel paths have been removed; this version targets headless openpyxl via the `excel-author` skill's conventions. Original: https://github.com/anthropics/financial-services
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,262 @@
|
||||
---
|
||||
title: "Excel Author — Build auditable financial workbooks headless via openpyxl"
|
||||
sidebar_label: "Excel Author"
|
||||
description: "Build auditable financial workbooks headless via openpyxl"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Excel Author
|
||||
|
||||
Build auditable financial workbooks headless via openpyxl.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/finance/excel-author` |
|
||||
| Path | `optional-skills/finance\excel-author` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Anthropic (adapted by Nous Research) |
|
||||
| License | Apache-2.0 |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `excel`, `openpyxl`, `finance`, `spreadsheet`, `modeling` |
|
||||
| Related skills | [`xlsx`](/docs/user-guide/skills/bundled/productivity/productivity-xlsx), [`pptx-author`](/docs/user-guide/skills/optional/finance/finance-pptx-author), [`dcf-model`](/docs/user-guide/skills/optional/finance/finance-dcf-model), [`comps-analysis`](/docs/user-guide/skills/optional/finance/finance-comps-analysis), [`lbo-model`](/docs/user-guide/skills/optional/finance/finance-lbo-model), [`3-statement-model`](/docs/user-guide/skills/optional/finance/finance-3-statement-model) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# excel-author
|
||||
|
||||
Produce an .xlsx file on disk using `openpyxl`. Follow the banker-grade conventions below so the model is auditable, flexible, and reviewable by someone other than the person who built it.
|
||||
|
||||
Adapted from Anthropic's `xlsx-author` and `audit-xls` skills in the [anthropics/financial-services](https://github.com/anthropics/financial-services) repo. The MCP / Office-JS / Cowork-specific branches of the originals are dropped — this skill assumes headless Python.
|
||||
|
||||
## Output contract
|
||||
|
||||
- Write to `./out/<name>.xlsx`. Create `./out/` if it does not exist.
|
||||
- Return the relative path in your final message so downstream tools can pick it up.
|
||||
- One logical model per file. Do not append to an existing workbook unless explicitly asked.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
pip install "openpyxl>=3.0"
|
||||
```
|
||||
|
||||
## Core conventions (non-negotiable)
|
||||
|
||||
### Blue / black / green cell color
|
||||
- **Blue** (`Font(color="0000FF")`) — hardcoded input a human entered. Revenue drivers, WACC inputs, terminal growth, market data.
|
||||
- **Black** (default) — formula. Every derived cell is a live Excel formula.
|
||||
- **Green** (`Font(color="006100")`) — link to another sheet or external file.
|
||||
|
||||
A reviewer can then scan the sheet and immediately see what's an assumption vs. what's computed.
|
||||
|
||||
### Formulas over hardcodes
|
||||
Every calculation cell MUST be a formula string, never a number computed in Python and pasted as a value.
|
||||
|
||||
```python
|
||||
# WRONG — silent bug waiting to happen
|
||||
ws["D20"] = revenue_prior_year * (1 + growth)
|
||||
|
||||
# CORRECT — flexes when the user changes the assumption
|
||||
ws["D20"] = "=D19*(1+$B$8)"
|
||||
```
|
||||
|
||||
The only hardcoded numbers permitted:
|
||||
1. Raw historical inputs (actual revenues, reported EBITDA, etc.)
|
||||
2. Assumption drivers the user is meant to flex (growth rates, WACC inputs, terminal g)
|
||||
3. Current market data (share price, debt balance) — with a cell comment documenting source + date
|
||||
|
||||
If you catch yourself computing a value in Python and writing the result, stop.
|
||||
|
||||
### Named ranges for cross-sheet references
|
||||
Use named ranges for any figure referenced from another sheet, a deck, or a memo.
|
||||
|
||||
```python
|
||||
from openpyxl.workbook.defined_name import DefinedName
|
||||
wb.defined_names["WACC"] = DefinedName("WACC", attr_text="Inputs!$C$8")
|
||||
# then elsewhere:
|
||||
calc["D30"] = "=D29/WACC"
|
||||
```
|
||||
|
||||
### Balance checks tab
|
||||
Include a `Checks` tab that ties everything and surfaces TRUE/FALSE:
|
||||
- Balance sheet balances (assets = liabilities + equity)
|
||||
- Cash flow ties to period-over-period cash change on the BS
|
||||
- Sum-of-parts ties to consolidated totals
|
||||
- No rogue hardcodes inside calc ranges
|
||||
|
||||
Example:
|
||||
```python
|
||||
checks = wb.create_sheet("Checks")
|
||||
checks["A2"] = "BS balances"
|
||||
checks["B2"] = "=IS!D20-IS!D21-IS!D22"
|
||||
checks["C2"] = "=ABS(B2)<0.01" # TRUE/FALSE
|
||||
```
|
||||
|
||||
### Cell comments on every hardcoded input
|
||||
Add the comment AS you create the cell, not later.
|
||||
|
||||
```python
|
||||
from openpyxl.comments import Comment
|
||||
ws["C2"] = 1_250_000_000
|
||||
ws["C2"].font = Font(color="0000FF")
|
||||
ws["C2"].comment = Comment("Source: 10-K FY2024, p.47, revenue line", "analyst")
|
||||
```
|
||||
|
||||
Format: `Source: [System/Document], [Date], [Reference], [URL if applicable]`.
|
||||
|
||||
Never defer sourcing. Never write `TODO: add source`.
|
||||
|
||||
## Skeleton: typical financial model
|
||||
|
||||
```python
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
||||
from openpyxl.comments import Comment
|
||||
from openpyxl.utils import get_column_letter
|
||||
from pathlib import Path
|
||||
|
||||
BLUE = Font(color="0000FF")
|
||||
BLACK = Font(color="000000")
|
||||
GREEN = Font(color="006100")
|
||||
BOLD = Font(bold=True)
|
||||
HEADER_FILL = PatternFill("solid", fgColor="1F4E79")
|
||||
HEADER_FONT = Font(color="FFFFFF", bold=True)
|
||||
|
||||
wb = Workbook()
|
||||
|
||||
# --- Inputs tab ---
|
||||
inp = wb.active
|
||||
inp.title = "Inputs"
|
||||
inp["A1"] = "MARKET DATA & KEY INPUTS"
|
||||
inp["A1"].font = HEADER_FONT
|
||||
inp["A1"].fill = HEADER_FILL
|
||||
inp.merge_cells("A1:C1")
|
||||
|
||||
inp["B3"] = "Revenue FY2024"
|
||||
inp["C3"] = 1_250_000_000
|
||||
inp["C3"].font = BLUE
|
||||
inp["C3"].comment = Comment("Source: 10-K FY2024 p.47", "model")
|
||||
|
||||
inp["B4"] = "Growth Rate"
|
||||
inp["C4"] = 0.12
|
||||
inp["C4"].font = BLUE
|
||||
|
||||
# --- Calc tab ---
|
||||
calc = wb.create_sheet("DCF")
|
||||
calc["B2"] = "Projected Revenue"
|
||||
calc["C2"] = "=Inputs!C3*(1+Inputs!C4)" # formula, black
|
||||
|
||||
# --- Checks tab ---
|
||||
chk = wb.create_sheet("Checks")
|
||||
chk["A2"] = "BS balances"
|
||||
chk["B2"] = "=ABS(BS!D20-BS!D21-BS!D22)<0.01"
|
||||
|
||||
Path("./out").mkdir(exist_ok=True)
|
||||
wb.save("./out/model.xlsx")
|
||||
```
|
||||
|
||||
## Section headers with merged cells
|
||||
|
||||
openpyxl quirk: when you merge, set the value on the top-left cell and style the full range separately.
|
||||
|
||||
```python
|
||||
ws["A7"] = "CASH FLOW PROJECTION"
|
||||
ws["A7"].font = HEADER_FONT
|
||||
ws.merge_cells("A7:H7")
|
||||
for col in range(1, 9): # A..H
|
||||
ws.cell(row=7, column=col).fill = HEADER_FILL
|
||||
```
|
||||
|
||||
## Sensitivity tables
|
||||
|
||||
Build with loops, not hardcoded formulas per cell. Rules:
|
||||
|
||||
- **Odd number of rows/cols** (5×5 or 7×7) — guarantees a true center cell.
|
||||
- **Center cell = base case.** The middle row/col header must equal the model's actual WACC and terminal g so the center output equals the base-case implied share price. That's the sanity check.
|
||||
- **Highlight the center cell** with medium-blue fill (`"BDD7EE"`) and bold.
|
||||
- Populate every cell with a full recalculation formula — never an approximation.
|
||||
|
||||
```python
|
||||
# 5x5 WACC (rows) x terminal growth (cols) sensitivity
|
||||
wacc_axis = [0.08, 0.085, 0.09, 0.095, 0.10] # center row = base 9.0%
|
||||
term_axis = [0.02, 0.025, 0.03, 0.035, 0.04] # center col = base 3.0%
|
||||
|
||||
start_row = 40
|
||||
ws.cell(row=start_row, column=1).value = "Implied Share Price ($)"
|
||||
ws.cell(row=start_row, column=1).font = BOLD
|
||||
|
||||
for j, g in enumerate(term_axis):
|
||||
ws.cell(row=start_row+1, column=2+j).value = g
|
||||
ws.cell(row=start_row+1, column=2+j).font = BLUE
|
||||
|
||||
for i, w in enumerate(wacc_axis):
|
||||
r = start_row + 2 + i
|
||||
ws.cell(row=r, column=1).value = w
|
||||
ws.cell(row=r, column=1).font = BLUE
|
||||
for j, g in enumerate(term_axis):
|
||||
c = 2 + j
|
||||
# Full DCF recalc formula (simplified for illustration).
|
||||
# In a real model this references the full projection block.
|
||||
ws.cell(row=r, column=c).value = (
|
||||
f"=SUMPRODUCT(FCF_range,1/(1+{w})^year_offset) + "
|
||||
f"FCF_terminal*(1+{g})/({w}-{g})/(1+{w})^terminal_year"
|
||||
)
|
||||
|
||||
# Highlight center cell (base case)
|
||||
center = ws.cell(row=start_row+2+len(wacc_axis)//2,
|
||||
column=2+len(term_axis)//2)
|
||||
center.fill = PatternFill("solid", fgColor="BDD7EE")
|
||||
center.font = BOLD
|
||||
```
|
||||
|
||||
## Recalculating before delivery
|
||||
|
||||
openpyxl writes formula strings but does not compute them. Excel recalculates on open, but downstream consumers (auto-check scripts, CI) need computed values.
|
||||
|
||||
Run LibreOffice or a dedicated recalc step before delivery:
|
||||
|
||||
```bash
|
||||
# LibreOffice headless recalc
|
||||
libreoffice --headless --calc --convert-to xlsx ./out/model.xlsx --outdir ./out/
|
||||
```
|
||||
|
||||
Or use a Python recalc helper (see `scripts/recalc.py` in this skill).
|
||||
|
||||
## Model layout planning
|
||||
|
||||
Before writing any formula:
|
||||
1. Define ALL section row positions
|
||||
2. Write ALL headers and labels
|
||||
3. Write ALL section dividers and blank rows
|
||||
4. THEN write formulas using the locked row positions
|
||||
|
||||
This prevents the cascading-formula-breakage pattern where inserting a header row after formulas are written shifts every downstream reference.
|
||||
|
||||
## Verify step-by-step with the user
|
||||
|
||||
For large models (DCFs, 3-statement, LBO), stop and show the user intermediate artifacts before continuing. Catching a wrong margin assumption before you've built downstream sensitivity tables saves an hour.
|
||||
|
||||
Checkpoint pattern:
|
||||
- After Inputs block → show raw inputs, confirm before projecting
|
||||
- After Revenue projections → confirm top line + growth
|
||||
- After FCF build → confirm the full schedule
|
||||
- After WACC → confirm inputs
|
||||
- After valuation → confirm the equity bridge
|
||||
- THEN build sensitivity tables
|
||||
|
||||
## When NOT to use this skill
|
||||
|
||||
- Users in a live Excel session with an Office MCP available — drive their live workbook instead.
|
||||
- Pure tabular data export with no formulas — `csv` or `pandas.to_excel` is simpler.
|
||||
- Dashboards / charts with heavy interactivity — use a real BI tool.
|
||||
|
||||
## Attribution
|
||||
|
||||
Conventions (blue/black/green, formulas-over-hardcodes, named ranges, sensitivity rules) adapted from Anthropic's Claude for Financial Services plugin suite, Apache-2.0 licensed. Original: https://github.com/anthropics/financial-services/tree/main/plugins/vertical-plugins/financial-analysis/skills/xlsx-author
|
||||
@@ -0,0 +1,309 @@
|
||||
---
|
||||
title: "Lbo Model — Build leveraged buyout workbooks with IRR/MOIC in Excel"
|
||||
sidebar_label: "Lbo Model"
|
||||
description: "Build leveraged buyout workbooks with IRR/MOIC in Excel"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Lbo Model
|
||||
|
||||
Build leveraged buyout workbooks with IRR/MOIC in Excel.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/finance/lbo-model` |
|
||||
| Path | `optional-skills/finance\lbo-model` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Anthropic (adapted by Nous Research) |
|
||||
| License | Apache-2.0 |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `finance`, `valuation`, `lbo`, `private-equity`, `excel`, `openpyxl`, `modeling` |
|
||||
| Related skills | [`excel-author`](/docs/user-guide/skills/optional/finance/finance-excel-author), [`pptx-author`](/docs/user-guide/skills/optional/finance/finance-pptx-author), [`dcf-model`](/docs/user-guide/skills/optional/finance/finance-dcf-model), [`3-statement-model`](/docs/user-guide/skills/optional/finance/finance-3-statement-model) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
## Environment
|
||||
|
||||
This skill assumes **headless openpyxl** — you are producing an .xlsx file on disk.
|
||||
Follow the `excel-author` skill's conventions for cell coloring, formulas, named ranges, and sensitivity tables.
|
||||
Recalculate before delivery: `python /path/to/excel-author/scripts/recalc.py ./out/model.xlsx`.
|
||||
|
||||
---
|
||||
|
||||
## TEMPLATE REQUIREMENT
|
||||
|
||||
**This skill uses templates for LBO models. Always check for an attached template file first.**
|
||||
|
||||
Before starting any LBO model:
|
||||
1. **If a template file is attached/provided**: Use that template's structure exactly - copy it and populate with the user's data
|
||||
2. **If no template is attached**: Ask the user: *"Do you have a specific LBO template you'd like me to use? If not, I can use the standard template which includes Sources & Uses, Operating Model, Debt Schedule, and Returns Analysis."*
|
||||
3. **If using the standard template**: Copy `examples/LBO_Model.xlsx` as your starting point and populate it with the user's assumptions
|
||||
|
||||
**IMPORTANT**: When a file like `LBO_Model.xlsx` is attached, you MUST use it as your template - do not build from scratch. Even if the template seems complex or has more features than needed, copy it and adapt it to the user's requirements. Never decide to "build from scratch" when a template is provided.
|
||||
|
||||
---
|
||||
|
||||
## CRITICAL INSTRUCTIONS — READ FIRST
|
||||
|
||||
Use Python/openpyxl. Write formula strings (`ws["D20"] = "=B5*B6"`), then run the `excel-author` skill's `recalc.py` helper before delivery.
|
||||
|
||||
### Core Principles
|
||||
* **Every calculation must be an Excel formula** - NEVER compute values in Python and hardcode results into cells. When using openpyxl, write `cell.value = "=B5*B6"` (formula string), NOT `cell.value = 1250` (computed result). The model must be dynamic and update when inputs change.
|
||||
* **Use the template structure** - Follow the organization in `examples/LBO_Model.xlsx` or the user's provided template. Do not invent your own layout.
|
||||
* **Use proper cell references** - All formulas should reference the appropriate cells. Never type numbers that should come from other cells.
|
||||
* **Maintain sign convention consistency** - Follow whatever sign convention the template uses (some use negative for outflows, some use positive). Be consistent throughout.
|
||||
* **Work section by section, verify with user at each step** - Complete one section fully, show the user what was built, run the section's verification checks, and get confirmation BEFORE moving to the next section. Do NOT build the entire model end-to-end and then present it — later sections depend on earlier ones, so catching a mistake in Sources & Uses after the returns are already built means rework everywhere.
|
||||
|
||||
### Formula Color Conventions
|
||||
* **Blue (0000FF)**: Hardcoded inputs - typed numbers that don't reference other cells
|
||||
* **Black (000000)**: Formulas with calculations - any formula using operators or functions (`=B4*B5`, `=SUM()`, `=-MAX(0,B4)`)
|
||||
* **Purple (800080)**: Links to cells on the **same tab** - direct references with no calculation (`=B9`, `=B45`)
|
||||
* **Green (008000)**: Links to cells on **different tabs** - cross-sheet references (`=Assumptions!B5`, `='Operating Model'!C10`)
|
||||
|
||||
### Fill Color Palette — Professional Blues & Greys (Default unless user/template specifies otherwise)
|
||||
* **Keep it minimal** — only use blues and greys for cell fills. Do NOT introduce greens, yellows, reds, or multiple accents. A professional LBO model uses restraint.
|
||||
* **Default fill palette:**
|
||||
* **Section headers** (Sources & Uses, Operating Model, etc.): Dark blue `#1F4E79` with white bold text
|
||||
* **Column headers** (Year 1, Year 2, etc.): Light blue `#D9E1F2` with black bold text
|
||||
* **Input cells**: Light grey `#F2F2F2` (or just white) — the blue *font* is the signal, fill is secondary
|
||||
* **Formula/calculated cells**: White, no fill
|
||||
* **Key outputs** (IRR, MOIC, Exit Equity): Medium blue `#BDD7EE` with black bold text
|
||||
* **That's the whole palette.** 3 blues + 1 grey + white. If the template uses its own colors, follow the template instead.
|
||||
* Note: The blue/black/purple/green **font** colors above are for distinguishing inputs vs formulas vs links. Those are separate from the **fill** palette here — both work together.
|
||||
|
||||
### Number Formatting Standards
|
||||
* **Currency**: `$#,##0;($#,##0);"-"` or `$#,##0.0` depending on template
|
||||
* **Percentages**: `0.0%` (one decimal)
|
||||
* **Multiples**: `0.0"x"` (one decimal)
|
||||
* **MOIC/Detailed Ratios**: `0.00"x"` (two decimals for precision)
|
||||
* **All numeric cells**: Right-aligned
|
||||
|
||||
---
|
||||
|
||||
### Clarify Requirements First
|
||||
|
||||
Before filling any formulas:
|
||||
|
||||
* **Examine the template structure** - Identify all sections, understand the timeline (which columns are which periods), note any existing formulas
|
||||
* **Ask the user if anything is unclear** - If the template structure, calculation methods, or requirements are ambiguous, ask before proceeding
|
||||
* **Confirm key assumptions** - Any key inputs, calculation preferences, or specific requirements
|
||||
* **ONLY AFTER understanding the template**, proceed to fill in formulas
|
||||
|
||||
---
|
||||
|
||||
## TEMPLATE ANALYSIS PHASE - DO THIS FIRST
|
||||
|
||||
Before filling any formulas, examine the template thoroughly:
|
||||
|
||||
1. **Map the structure** - Identify where each section lives and how they relate to each other. Note which sections feed into others.
|
||||
|
||||
2. **Understand the timeline** - Which columns represent which periods? Is there a "Closing" or "Pro Forma" column? Where does the projection period start?
|
||||
|
||||
3. **Identify input vs formula cells** - Templates often use color coding, borders, or shading to indicate which cells need inputs vs formulas. Respect these conventions.
|
||||
|
||||
4. **Read existing labels carefully** - The row labels tell you exactly what calculation is expected. Don't assume - read what the template is asking for.
|
||||
|
||||
5. **Check for existing formulas** - Some templates come partially filled. Don't overwrite working formulas unless specifically asked.
|
||||
|
||||
6. **Note template-specific conventions** - Sign conventions, subtotal structures, how sections are organized, whether there are separate tabs for different components, etc.
|
||||
|
||||
---
|
||||
|
||||
## FILLING FORMULAS - GENERAL APPROACH
|
||||
|
||||
For each cell that needs a formula, follow this hierarchy:
|
||||
|
||||
### Step 1: Check the Template
|
||||
* Does the cell already have a formula? If yes, verify it's correct and move on.
|
||||
* Is there a comment or note indicating the expected calculation?
|
||||
* Does the row/column label make the calculation obvious?
|
||||
* Do neighboring cells show a pattern you should follow?
|
||||
|
||||
### Step 2: Check the User's Instructions
|
||||
* Did the user specify a particular calculation method?
|
||||
* Are there stated assumptions that affect this formula?
|
||||
* Any special requirements mentioned?
|
||||
|
||||
### Step 3: Apply Standard Practice
|
||||
* If neither template nor user specifies, use standard LBO modeling conventions
|
||||
* Document any assumptions you make
|
||||
* If genuinely uncertain, ask the user
|
||||
|
||||
---
|
||||
|
||||
## COMMON PROBLEM AREAS
|
||||
|
||||
The following calculation patterns frequently cause issues across LBO models. Pay special attention when you encounter these:
|
||||
|
||||
### Balancing Sections
|
||||
* When two sections must equal (e.g., Sources = Uses), one item is typically the "plug" (balancing figure)
|
||||
* Identify which item is the plug and calculate it as the difference
|
||||
|
||||
### Tax Calculations
|
||||
* Tax formulas should only reference the relevant income line and tax rate
|
||||
* Should NOT reference unrelated sections (e.g., debt schedules)
|
||||
* Consider whether losses create tax shields or are simply ignored
|
||||
|
||||
### Interest and Circular References
|
||||
* Interest calculations can create circularity if they reference balances affected by cash flows
|
||||
* Use **Beginning Balance** (not average or ending) to break circular references
|
||||
* Pattern: Interest → Cash Flow → Paydown → Ending Balance (if interest uses ending balance, this circles back)
|
||||
|
||||
### Debt Paydown / Cash Sweeps
|
||||
* When multiple debt tranches exist, there's usually a priority order
|
||||
* Cash sweep should respect the priority waterfall
|
||||
* Balances cannot go negative - use MAX or MIN functions appropriately
|
||||
|
||||
### Returns Calculations (IRR/MOIC)
|
||||
* Cash flows must have correct signs: Investment = negative, Proceeds = positive
|
||||
* If using XIRR, need corresponding dates
|
||||
* If using IRR, cash flows should be in consecutive periods
|
||||
* MOIC = Total Proceeds / Total Investment
|
||||
|
||||
### Sensitivity Tables
|
||||
* **Use ODD dimensions** (5×5 or 7×7) — never 4×4 or 6×6. Odd dimensions guarantee a true center cell.
|
||||
* **Center cell = base case.** Build the row and column axis values symmetrically around the model's actual assumptions (e.g., if base entry multiple = 10.0x, axis = `[8.0x, 9.0x, 10.0x, 11.0x, 12.0x]`). The center cell's IRR/MOIC MUST then equal the model's actual IRR/MOIC output — this is the proof the table is wired correctly.
|
||||
* **Highlight the center cell** — medium-blue fill (`#BDD7EE`) + bold font so the base case is visually anchored.
|
||||
* Excel's DATA TABLE function may not work with openpyxl — instead write explicit formulas that reference row/column headers
|
||||
* Each cell should show a DIFFERENT value — if all same, formulas aren't varying correctly
|
||||
* Use mixed references (e.g., `$A5` for row input, `B$4` for column input)
|
||||
|
||||
---
|
||||
|
||||
## VERIFICATION CHECKLIST - RUN AFTER COMPLETION
|
||||
|
||||
### Run Formula Validation
|
||||
```bash
|
||||
python /path/to/excel-author/scripts/recalc.py model.xlsx
|
||||
```
|
||||
Must return success with zero errors.
|
||||
|
||||
### Section Balancing
|
||||
- [ ] Any sections that must balance (Sources/Uses, Assets/Liabilities) balance exactly
|
||||
- [ ] Plug items are calculated correctly as the balancing figure
|
||||
- [ ] Amounts that should match across sections are consistent
|
||||
|
||||
### Income/Operating Projections
|
||||
- [ ] Revenue/top-line builds correctly from drivers or growth rates
|
||||
- [ ] All cost and expense items calculated appropriately
|
||||
- [ ] Subtotals and totals sum correctly
|
||||
- [ ] Margins and ratios are reasonable
|
||||
- [ ] Links to assumptions are correct
|
||||
|
||||
### Balance Sheet (if applicable)
|
||||
- [ ] Assets = Liabilities + Equity (must balance)
|
||||
- [ ] All items link to appropriate schedules or roll-forwards
|
||||
- [ ] Beginning balances = prior period ending balances
|
||||
- [ ] Check row included and shows zero
|
||||
|
||||
### Cash Flow (if applicable)
|
||||
- [ ] Starts with correct income figure
|
||||
- [ ] Non-cash items added/subtracted appropriately
|
||||
- [ ] Working capital changes have correct signs
|
||||
- [ ] Ending Cash = Beginning Cash + Net Cash Flow
|
||||
- [ ] Cash balances are consistent across statements
|
||||
|
||||
### Supporting Schedules
|
||||
- [ ] Roll-forward schedules balance (Beginning + Changes = Ending)
|
||||
- [ ] Schedules link correctly to main statements
|
||||
- [ ] Calculated items use appropriate drivers
|
||||
- [ ] All periods are calculated consistently
|
||||
|
||||
### Debt/Financing Schedules (if applicable)
|
||||
- [ ] Beginning balances tie to sources or prior period
|
||||
- [ ] Interest calculated on appropriate balance (typically beginning)
|
||||
- [ ] Paydowns respect cash availability and priority
|
||||
- [ ] Ending balances cannot be negative
|
||||
- [ ] Totals sum tranches correctly
|
||||
|
||||
### Returns/Output Analysis
|
||||
- [ ] Exit/terminal values calculated correctly
|
||||
- [ ] All relevant adjustments included
|
||||
- [ ] Cash flow signs are correct (negative for investment, positive for proceeds)
|
||||
- [ ] IRR/MOIC formulas reference complete ranges
|
||||
- [ ] Results are reasonable for the scenario
|
||||
|
||||
### Sensitivity Tables (if applicable)
|
||||
- [ ] Grid dimensions are ODD (5×5 or 7×7) — there is a true center cell
|
||||
- [ ] Row and column axis values are symmetric around the base case (`[base-2Δ, base-Δ, base, base+Δ, base+2Δ]`)
|
||||
- [ ] Center cell output equals the model's actual IRR/MOIC — confirms the table is wired correctly
|
||||
- [ ] Center cell is highlighted (medium-blue fill `#BDD7EE`, bold font)
|
||||
- [ ] Row and column headers contain appropriate input values
|
||||
- [ ] Each data cell contains a formula (not hardcoded)
|
||||
- [ ] Each data cell shows a DIFFERENT value
|
||||
- [ ] Values move in expected directions (higher exit multiple → higher IRR, etc.)
|
||||
|
||||
### Formatting
|
||||
- [ ] Hardcoded inputs are blue (0000FF)
|
||||
- [ ] Calculated formulas are black (000000)
|
||||
- [ ] Same-tab links are purple (800080)
|
||||
- [ ] Cross-tab links are green (008000)
|
||||
- [ ] All numbers are right-aligned
|
||||
- [ ] Appropriate number formats applied throughout
|
||||
- [ ] No cells show error values (#REF!, #DIV/0!, #VALUE!, #NAME?)
|
||||
|
||||
### Logical Sanity Checks
|
||||
- [ ] Numbers are reasonable order of magnitude
|
||||
- [ ] Trends make sense (growth, decline, stabilization as expected)
|
||||
- [ ] No obviously wrong values (negative where should be positive, impossible percentages, etc.)
|
||||
- [ ] Key outputs are within reasonable ranges for the type of analysis
|
||||
|
||||
---
|
||||
|
||||
## COMMON ERRORS TO AVOID
|
||||
|
||||
| Error | What Goes Wrong | How to Fix |
|
||||
|-------|-----------------|------------|
|
||||
| Hardcoding calculated values | Model doesn't update when inputs change | Always use formulas that reference source cells |
|
||||
| Wrong cell references after copying | Formulas point to wrong cells | Verify all links, use appropriate $ anchoring |
|
||||
| Circular reference errors | Model can't calculate | Use beginning balances for interest-type calcs, break the circle |
|
||||
| Sections don't balance | Totals that should match don't | Ensure one item is the plug (calculated as difference) |
|
||||
| Negative balances where impossible | Paying/using more than available | Use MAX(0, ...) or MIN functions appropriately |
|
||||
| IRR/return errors | Wrong signs or incomplete ranges | Check cash flow signs and ensure formula covers all periods |
|
||||
| Sensitivity table shows same value | Formula not varying with inputs | Check cell references - need mixed references ($A5, B$4) |
|
||||
| Roll-forwards don't tie | Beginning ≠ prior ending | Verify links between periods |
|
||||
| Inconsistent sign conventions | Additions become subtractions or vice versa | Follow template's convention consistently throughout |
|
||||
|
||||
---
|
||||
|
||||
## WORKING WITH THE USER — SECTION-BY-SECTION CHECKPOINTS
|
||||
|
||||
* **If the template structure is unclear**, ask before proceeding
|
||||
* **If the user's requirements conflict with the template**, confirm their preference
|
||||
* **After completing each major section**, STOP and verify with the user before continuing:
|
||||
- **After Sources & Uses** → show the balanced table, confirm the plug is correct, get sign-off before building the operating model
|
||||
- **After Operating Model / Projections** → show the projected P&L, confirm growth rates and margins look right, get sign-off before the debt schedule
|
||||
- **After Debt Schedule** → show beginning/ending balances and interest, confirm the waterfall logic, get sign-off before returns
|
||||
- **After Returns (IRR/MOIC)** → show the cash flow series and outputs, confirm signs and ranges, get sign-off before sensitivity tables
|
||||
- **After Sensitivity Tables** → show that each cell varies, confirm the base case lands where expected
|
||||
* **If errors are found during verification**, fix them before moving to the next section
|
||||
* **Show your work** - explain key formulas or assumptions when helpful
|
||||
* **Never present a completed model without having checked in at each section** — it's faster to catch a wrong cell reference at the source than to trace it backwards from a broken IRR
|
||||
|
||||
---
|
||||
|
||||
**This skill produces investment banking-quality LBO models by filling templates with correct formulas, proper formatting, and validated calculations. The skill adapts to any template structure while ensuring financial accuracy and professional presentation standards.**
|
||||
|
||||
|
||||
## Data sources — MCP first, web fallback
|
||||
|
||||
Many passages below say "use the S&P Kensho MCP / Daloopa MCP / FactSet MCP". Those are commercial financial-data MCPs from the original Cowork plugin context. In Hermes:
|
||||
|
||||
- **If you have any structured financial-data MCP configured** (Hermes supports MCP — see `native-mcp` skill), prefer it for point-in-time comps, precedent transactions, and filings.
|
||||
- **Otherwise**, fall back to:
|
||||
- `web_search` / `web_extract` against SEC EDGAR (`https://www.sec.gov/cgi-bin/browse-edgar`) for US filings
|
||||
- Company IR pages for press releases, earnings decks
|
||||
- `browser_navigate` for interactive data portals
|
||||
- User-provided data (explicitly ask when the context doesn't have it)
|
||||
- **Never fabricate**. If a multiple, precedent, or filing number can't be sourced, flag the cell as `[UNSOURCED]` and surface it to the user.
|
||||
|
||||
## Attribution
|
||||
|
||||
This skill is adapted from Anthropic's Claude for Financial Services plugin suite (Apache-2.0). The Office-JS / Cowork live-Excel paths have been removed; this version targets headless openpyxl via the `excel-author` skill's conventions. Original: https://github.com/anthropics/financial-services
|
||||
@@ -0,0 +1,162 @@
|
||||
---
|
||||
title: "Merger Model — Build M&A accretion/dilution workbooks in Excel"
|
||||
sidebar_label: "Merger Model"
|
||||
description: "Build M&A accretion/dilution workbooks in Excel"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Merger Model
|
||||
|
||||
Build M&A accretion/dilution workbooks in Excel.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/finance/merger-model` |
|
||||
| Path | `optional-skills/finance\merger-model` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Anthropic (adapted by Nous Research) |
|
||||
| License | Apache-2.0 |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `finance`, `m-and-a`, `merger`, `accretion-dilution`, `excel`, `openpyxl`, `modeling`, `investment-banking` |
|
||||
| Related skills | [`excel-author`](/docs/user-guide/skills/optional/finance/finance-excel-author), [`pptx-author`](/docs/user-guide/skills/optional/finance/finance-pptx-author), [`dcf-model`](/docs/user-guide/skills/optional/finance/finance-dcf-model), [`3-statement-model`](/docs/user-guide/skills/optional/finance/finance-3-statement-model) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
## Environment
|
||||
|
||||
This skill assumes **headless openpyxl** — you are producing an .xlsx file on disk.
|
||||
Follow the `excel-author` skill's conventions for cell coloring, formulas, named ranges, and sensitivity tables.
|
||||
Recalculate before delivery: `python /path/to/excel-author/scripts/recalc.py ./out/model.xlsx`.
|
||||
|
||||
# Merger Model
|
||||
|
||||
Build accretion/dilution analysis for M&A transactions. Models pro forma EPS impact, synergy sensitivities, and purchase price allocation. Use when evaluating a potential acquisition, preparing merger consequences analysis for a pitch, or advising on deal terms.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Gather Inputs
|
||||
|
||||
**Acquirer:**
|
||||
- Company name, current share price, shares outstanding
|
||||
- LTM and NTM EPS (GAAP and adjusted)
|
||||
- P/E multiple
|
||||
- Pre-tax cost of debt, tax rate
|
||||
- Cash on balance sheet, existing debt
|
||||
|
||||
**Target:**
|
||||
- Company name, current share price, shares outstanding (if public)
|
||||
- LTM and NTM EPS or net income
|
||||
- Enterprise value or equity value
|
||||
|
||||
**Deal Terms:**
|
||||
- Offer price per share (or premium to current)
|
||||
- Consideration mix: % cash vs. % stock
|
||||
- New debt raised to fund cash portion
|
||||
- Expected synergies (revenue and cost) and phase-in timeline
|
||||
- Transaction fees and financing costs
|
||||
- Expected close date
|
||||
|
||||
### Step 2: Purchase Price Analysis
|
||||
|
||||
| Item | Value |
|
||||
|------|-------|
|
||||
| Offer price per share | |
|
||||
| Premium to current | |
|
||||
| Equity value | |
|
||||
| Plus: net debt assumed | |
|
||||
| Enterprise value | |
|
||||
| EV / EBITDA implied | |
|
||||
| P/E implied | |
|
||||
|
||||
### Step 3: Sources & Uses
|
||||
|
||||
| Sources | $ | Uses | $ |
|
||||
|---------|---|------|---|
|
||||
| New debt | | Equity purchase price | |
|
||||
| Cash on hand | | Refinance target debt | |
|
||||
| New equity issued | | Transaction fees | |
|
||||
| | | Financing fees | |
|
||||
| **Total** | | **Total** | |
|
||||
|
||||
### Step 4: Pro Forma EPS (Accretion / Dilution)
|
||||
|
||||
Calculate year-by-year (Year 1-3):
|
||||
|
||||
| | Standalone | Pro Forma | Accretion/(Dilution) |
|
||||
|---|-----------|-----------|---------------------|
|
||||
| Acquirer net income | | | |
|
||||
| Target net income | | | |
|
||||
| Synergies (after tax) | | | |
|
||||
| Foregone interest on cash (after tax) | | | |
|
||||
| New debt interest (after tax) | | | |
|
||||
| Intangible amortization (after tax) | | | |
|
||||
| Pro forma net income | | | |
|
||||
| Pro forma shares | | | |
|
||||
| **Pro forma EPS** | | | |
|
||||
| **Accretion / (Dilution) %** | | | |
|
||||
|
||||
### Step 5: Sensitivity Analysis
|
||||
|
||||
**Accretion/Dilution vs. Synergies and Offer Premium:**
|
||||
|
||||
| | $0M syn | $25M syn | $50M syn | $75M syn | $100M syn |
|
||||
|---|---------|----------|----------|----------|-----------|
|
||||
| 15% premium | | | | | |
|
||||
| 20% premium | | | | | |
|
||||
| 25% premium | | | | | |
|
||||
| 30% premium | | | | | |
|
||||
|
||||
**Accretion/Dilution vs. Cash/Stock Mix:**
|
||||
|
||||
| | 100% cash | 75/25 | 50/50 | 25/75 | 100% stock |
|
||||
|---|-----------|-------|-------|-------|------------|
|
||||
| Year 1 | | | | | |
|
||||
| Year 2 | | | | | |
|
||||
|
||||
### Step 6: Breakeven Synergies
|
||||
|
||||
Calculate the minimum synergies needed for the deal to be EPS-neutral in Year 1.
|
||||
|
||||
### Step 7: Output
|
||||
|
||||
- Excel workbook with:
|
||||
- Assumptions tab
|
||||
- Sources & uses
|
||||
- Pro forma income statement
|
||||
- Accretion/dilution summary
|
||||
- Sensitivity tables
|
||||
- Breakeven analysis
|
||||
- One-page merger consequences summary for pitch book
|
||||
|
||||
## Important Notes
|
||||
|
||||
- Always show both GAAP and adjusted (cash) EPS where relevant
|
||||
- Stock deals: use acquirer's current price for exchange ratio, note dilution from new shares
|
||||
- Include purchase price allocation — goodwill and intangible amortization matter for GAAP EPS
|
||||
- Synergy phase-in is critical — Year 1 is often only 25-50% of run-rate synergies
|
||||
- Don't forget foregone interest income on cash used and new interest expense on debt raised
|
||||
- Tax rate on synergies and interest adjustments should match the acquirer's marginal rate
|
||||
|
||||
|
||||
## Data sources — MCP first, web fallback
|
||||
|
||||
Many passages below say "use the S&P Kensho MCP / Daloopa MCP / FactSet MCP". Those are commercial financial-data MCPs from the original Cowork plugin context. In Hermes:
|
||||
|
||||
- **If you have any structured financial-data MCP configured** (Hermes supports MCP — see `native-mcp` skill), prefer it for point-in-time comps, precedent transactions, and filings.
|
||||
- **Otherwise**, fall back to:
|
||||
- `web_search` / `web_extract` against SEC EDGAR (`https://www.sec.gov/cgi-bin/browse-edgar`) for US filings
|
||||
- Company IR pages for press releases, earnings decks
|
||||
- `browser_navigate` for interactive data portals
|
||||
- User-provided data (explicitly ask when the context doesn't have it)
|
||||
- **Never fabricate**. If a multiple, precedent, or filing number can't be sourced, flag the cell as `[UNSOURCED]` and surface it to the user.
|
||||
|
||||
## Attribution
|
||||
|
||||
This skill is adapted from Anthropic's Claude for Financial Services plugin suite (Apache-2.0). The Office-JS / Cowork live-Excel paths have been removed; this version targets headless openpyxl via the `excel-author` skill's conventions. Original: https://github.com/anthropics/financial-services
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
title: "Polymarket — Query Polymarket: markets, prices, orderbooks, history"
|
||||
sidebar_label: "Polymarket"
|
||||
description: "Query Polymarket: markets, prices, orderbooks, history"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Polymarket
|
||||
|
||||
Query Polymarket: markets, prices, orderbooks, history.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/finance/polymarket` |
|
||||
| Path | `optional-skills/finance\polymarket` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hermes Agent + Teknium |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Polymarket — Prediction Market Data
|
||||
|
||||
Query prediction market data from Polymarket using their public REST APIs.
|
||||
All endpoints are read-only and require zero authentication.
|
||||
|
||||
See `references/api-endpoints.md` for the full endpoint reference with curl examples.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks about prediction markets, betting odds, or event probabilities
|
||||
- User wants to know "what are the odds of X happening?"
|
||||
- User asks about Polymarket specifically
|
||||
- User wants market prices, orderbook data, or price history
|
||||
- User asks to monitor or track prediction market movements
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- **Events** contain one or more **Markets** (1:many relationship)
|
||||
- **Markets** are binary outcomes with Yes/No prices between 0.00 and 1.00
|
||||
- Prices ARE probabilities: price 0.65 means the market thinks 65% likely
|
||||
- `outcomePrices` field: JSON-encoded array like `["0.80", "0.20"]`
|
||||
- `clobTokenIds` field: JSON-encoded array of two token IDs [Yes, No] for price/book queries
|
||||
- `conditionId` field: hex string used for price history queries
|
||||
- Volume is in USDC (US dollars)
|
||||
|
||||
## Three Public APIs
|
||||
|
||||
1. **Gamma API** at `gamma-api.polymarket.com` — Discovery, search, browsing
|
||||
2. **CLOB API** at `clob.polymarket.com` — Real-time prices, orderbooks, history
|
||||
3. **Data API** at `data-api.polymarket.com` — Trades, open interest
|
||||
|
||||
## Typical Workflow
|
||||
|
||||
When a user asks about prediction market odds:
|
||||
|
||||
1. **Search** using the Gamma API public-search endpoint with their query
|
||||
2. **Parse** the response — extract events and their nested markets
|
||||
3. **Present** market question, current prices as percentages, and volume
|
||||
4. **Deep dive** if asked — use clobTokenIds for orderbook, conditionId for history
|
||||
|
||||
## Presenting Results
|
||||
|
||||
Format prices as percentages for readability:
|
||||
- outcomePrices `["0.652", "0.348"]` becomes "Yes: 65.2%, No: 34.8%"
|
||||
- Always show the market question and probability
|
||||
- Include volume when available
|
||||
|
||||
Example: `"Will X happen?" — 65.2% Yes ($1.2M volume)`
|
||||
|
||||
## Parsing Double-Encoded Fields
|
||||
|
||||
The Gamma API returns `outcomePrices`, `outcomes`, and `clobTokenIds` as JSON strings
|
||||
inside JSON responses (double-encoded). When processing with Python, parse them with
|
||||
`json.loads(market['outcomePrices'])` to get the actual array.
|
||||
|
||||
## Rate Limits
|
||||
|
||||
Generous — unlikely to hit for normal usage:
|
||||
- Gamma: 4,000 requests per 10 seconds (general)
|
||||
- CLOB: 9,000 requests per 10 seconds (general)
|
||||
- Data: 1,000 requests per 10 seconds (general)
|
||||
|
||||
## Limitations
|
||||
|
||||
- This skill is read-only — it does not support placing trades
|
||||
- Trading requires wallet-based crypto authentication (EIP-712 signatures)
|
||||
- Some new markets may have empty price history
|
||||
- Geographic restrictions apply to trading but read-only data is globally accessible
|
||||
@@ -0,0 +1,191 @@
|
||||
---
|
||||
title: "Pptx Author — Build PowerPoint decks headless with python-pptx"
|
||||
sidebar_label: "Pptx Author"
|
||||
description: "Build PowerPoint decks headless with python-pptx"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Pptx Author
|
||||
|
||||
Build PowerPoint decks headless with python-pptx.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/finance/pptx-author` |
|
||||
| Path | `optional-skills/finance\pptx-author` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Anthropic (adapted by Nous Research) |
|
||||
| License | Apache-2.0 |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `powerpoint`, `pptx`, `python-pptx`, `presentation`, `finance` |
|
||||
| Related skills | [`excel-author`](/docs/user-guide/skills/optional/finance/finance-excel-author), [`powerpoint`](/docs/user-guide/skills/bundled/productivity/productivity-powerpoint) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# pptx-author
|
||||
|
||||
Produce a .pptx file on disk using `python-pptx`. Use when you need to deliver a deck as a file artifact, not drive a live PowerPoint session.
|
||||
|
||||
Adapted from Anthropic's `pptx-author` and `pitch-deck` skills in [anthropics/financial-services](https://github.com/anthropics/financial-services). The MCP / Office-JS branches of the originals are dropped — this assumes headless Python.
|
||||
|
||||
For the broader, already-shipped PowerPoint authoring skill (slides, speaker notes, embeds, media), see the built-in `powerpoint` skill. This skill is a lighter-weight pattern tuned for model-backed decks (pitch decks, IC memos, earnings notes) where every number must trace to a source workbook.
|
||||
|
||||
## Output contract
|
||||
|
||||
- Write to `./out/<name>.pptx`. Create `./out/` if it does not exist.
|
||||
- Return the relative path in your final message.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
pip install "python-pptx>=0.6"
|
||||
```
|
||||
|
||||
## Core conventions
|
||||
|
||||
### One idea per slide
|
||||
Title states the takeaway; body supports it. A slide titled "Q3 Revenue" is weak; "Revenue growth accelerated to 14% Y/Y in Q3" is strong.
|
||||
|
||||
### Every number traces to the model
|
||||
If a figure on a slide came from `./out/model.xlsx`, footnote the sheet and cell.
|
||||
|
||||
```
|
||||
Revenue: $1,250M (Source: model.xlsx, Inputs!C3)
|
||||
```
|
||||
|
||||
Never transcribe numbers from memory or from a summary — open the workbook, read the named range, and bind the deck value to it programmatically when you can.
|
||||
|
||||
### Use the firm template when one is mounted
|
||||
If `./templates/firm-template.pptx` exists, load it so the deck inherits branded colors, fonts, and master layouts.
|
||||
|
||||
```python
|
||||
from pptx import Presentation
|
||||
from pathlib import Path
|
||||
|
||||
template = Path("./templates/firm-template.pptx")
|
||||
prs = Presentation(str(template)) if template.exists() else Presentation()
|
||||
```
|
||||
|
||||
### Charts: PNG-from-model beats native pptx charts
|
||||
When fidelity matters (the model's chart styling must match the deck exactly), render the chart to PNG from the source workbook and embed the image. Native `pptx.chart` charts are fragile and often don't match firm conventions.
|
||||
|
||||
```python
|
||||
from pptx.util import Inches
|
||||
slide.shapes.add_picture("./out/charts/football_field.png",
|
||||
Inches(1), Inches(2),
|
||||
width=Inches(8))
|
||||
```
|
||||
|
||||
### No external sends
|
||||
This skill writes a file. It never emails, uploads, or posts. Orchestration layers handle delivery.
|
||||
|
||||
## Skeleton
|
||||
|
||||
```python
|
||||
from pptx import Presentation
|
||||
from pptx.util import Inches, Pt
|
||||
from pptx.dml.color import RGBColor
|
||||
from pathlib import Path
|
||||
|
||||
template = Path("./templates/firm-template.pptx")
|
||||
prs = Presentation(str(template)) if template.exists() else Presentation()
|
||||
|
||||
# Title slide
|
||||
slide = prs.slides.add_slide(prs.slide_layouts[0])
|
||||
slide.shapes.title.text = "Project Aurora — Strategic Alternatives"
|
||||
slide.placeholders[1].text = "Preliminary Discussion Materials"
|
||||
|
||||
# Valuation summary slide (title-only layout)
|
||||
slide = prs.slides.add_slide(prs.slide_layouts[5])
|
||||
slide.shapes.title.text = "Valuation implies $38–$52 per share across methodologies"
|
||||
|
||||
# Add a table bound to model outputs
|
||||
rows, cols = 5, 4
|
||||
tbl_shape = slide.shapes.add_table(rows, cols,
|
||||
Inches(0.5), Inches(1.5),
|
||||
Inches(9), Inches(3))
|
||||
tbl = tbl_shape.table
|
||||
headers = ["Methodology", "Low ($)", "Mid ($)", "High ($)"]
|
||||
for c, h in enumerate(headers):
|
||||
tbl.cell(0, c).text = h
|
||||
|
||||
# In a real deck, read these from the model workbook with openpyxl
|
||||
data = [
|
||||
("Trading comps", "35", "41", "48"),
|
||||
("Precedent M&A", "39", "45", "52"),
|
||||
("DCF (base)", "36", "43", "51"),
|
||||
("LBO (10% IRR)", "33", "38", "44"),
|
||||
]
|
||||
for r, row in enumerate(data, start=1):
|
||||
for c, val in enumerate(row):
|
||||
tbl.cell(r, c).text = val
|
||||
|
||||
# Embed a chart rendered from the model
|
||||
slide = prs.slides.add_slide(prs.slide_layouts[5])
|
||||
slide.shapes.title.text = "Football field — current price $42"
|
||||
slide.shapes.add_picture("./out/charts/football_field.png",
|
||||
Inches(1), Inches(1.8), width=Inches(8))
|
||||
|
||||
Path("./out").mkdir(exist_ok=True)
|
||||
prs.save("./out/pitch-aurora.pptx")
|
||||
```
|
||||
|
||||
## Binding deck numbers to the source workbook
|
||||
|
||||
Read named ranges or specific cells from your Excel model so deck numbers never drift.
|
||||
|
||||
```python
|
||||
from openpyxl import load_workbook
|
||||
|
||||
wb = load_workbook("./out/model.xlsx", data_only=True)
|
||||
def nr(name):
|
||||
"""Resolve a named range to its current computed value."""
|
||||
rng = wb.defined_names[name]
|
||||
sheet, coord = next(rng.destinations)
|
||||
return wb[sheet][coord].value
|
||||
|
||||
revenue_fy24 = nr("RevenueFY24")
|
||||
implied_mid = nr("ImpliedSharePriceBase")
|
||||
```
|
||||
|
||||
Then build deck content using those values:
|
||||
```python
|
||||
slide.shapes.title.text = f"Implied share price of ${implied_mid:.2f} (base case)"
|
||||
```
|
||||
|
||||
Remember to recalculate the workbook before reading it — openpyxl only sees computed values if something has already calculated the sheet. Run the recalc helper in the `excel-author` skill first, or open/save through a real Excel session.
|
||||
|
||||
## Slide-type checklist for pitch decks
|
||||
|
||||
A typical banking pitch deck follows this structure. Not prescriptive, but useful as a starting skeleton:
|
||||
|
||||
1. Cover / title
|
||||
2. Disclaimer
|
||||
3. Table of contents
|
||||
4. Situation overview
|
||||
5. Company snapshot (the target)
|
||||
6. Market / sector context
|
||||
7. Valuation summary (football field) — the money slide
|
||||
8. Trading comps detail
|
||||
9. Precedent transactions detail
|
||||
10. DCF summary
|
||||
11. Illustrative LBO / sponsor case
|
||||
12. Process considerations
|
||||
13. Appendix
|
||||
|
||||
## When NOT to use this skill
|
||||
|
||||
- Users in a live PowerPoint session with an Office MCP available — drive their live doc instead.
|
||||
- Non-financial slideware (quarterly all-hands, marketing decks) — use the broader `powerpoint` skill.
|
||||
- Decks with heavy animation, transitions, or speaker notes — use the broader `powerpoint` skill.
|
||||
|
||||
## Attribution
|
||||
|
||||
Conventions adapted from Anthropic's Claude for Financial Services plugin suite, Apache-2.0 licensed. Original: https://github.com/anthropics/financial-services/tree/main/plugins/agent-plugins/pitch-agent/skills/pptx-author
|
||||
@@ -0,0 +1,112 @@
|
||||
---
|
||||
title: "Stocks — Stock quotes, history, search, compare, crypto via Yahoo"
|
||||
sidebar_label: "Stocks"
|
||||
description: "Stock quotes, history, search, compare, crypto via Yahoo"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Stocks
|
||||
|
||||
Stock quotes, history, search, compare, crypto via Yahoo.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/finance/stocks` |
|
||||
| Path | `optional-skills/finance\stocks` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | Mibay (Mibayy), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Stocks`, `Finance`, `Market`, `Crypto`, `Investing` |
|
||||
| Related skills | [`dcf-model`](/docs/user-guide/skills/optional/finance/finance-dcf-model), [`comps-analysis`](/docs/user-guide/skills/optional/finance/finance-comps-analysis), [`lbo-model`](/docs/user-guide/skills/optional/finance/finance-lbo-model) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Stocks Skill
|
||||
|
||||
Read-only market data via Yahoo Finance. Five commands: `quote`, `search`,
|
||||
`history`, `compare`, `crypto`. Python stdlib only — no API key, no pip
|
||||
installs. Yahoo's endpoint is unofficial and may rate-limit or change.
|
||||
|
||||
## When to Use
|
||||
|
||||
- User asks for a current stock price (AAPL, TSLA, MSFT, ...)
|
||||
- User wants to look up a ticker by company name
|
||||
- User wants OHLCV history or performance over a date range
|
||||
- User wants to compare several tickers side by side
|
||||
- User asks for a crypto price (BTC, ETH, SOL, ...)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Python 3.8+ stdlib only. Optional: set `ALPHA_VANTAGE_KEY` to enrich
|
||||
`market_cap`, `pe_ratio`, and 52-week levels when Yahoo's crumb-protected
|
||||
fields come back null. Free key: https://www.alphavantage.co/support/#api-key
|
||||
|
||||
## How to Run
|
||||
|
||||
Invoke through the `terminal` tool. Once installed:
|
||||
|
||||
```
|
||||
SCRIPT=~/.hermes/skills/finance/stocks/scripts/stocks_client.py
|
||||
python $SCRIPT quote AAPL
|
||||
```
|
||||
|
||||
All output is JSON on stdout — pipe through `jq` if you want to slice it.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```
|
||||
python $SCRIPT quote AAPL
|
||||
python $SCRIPT quote AAPL MSFT GOOGL TSLA
|
||||
python $SCRIPT search "Tesla"
|
||||
python $SCRIPT history NVDA --range 6mo
|
||||
python $SCRIPT compare AAPL MSFT GOOGL
|
||||
python $SCRIPT crypto BTC ETH SOL
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
### `quote SYMBOL [SYMBOL2 ...]`
|
||||
|
||||
Current price, change, change%, volume, 52-week high/low.
|
||||
|
||||
### `search QUERY`
|
||||
|
||||
Find tickers by company name. Returns top 5: symbol, name, exchange, type.
|
||||
|
||||
### `history SYMBOL [--range RANGE]`
|
||||
|
||||
Daily OHLCV plus stats (min, max, avg, total return %). Ranges: `1mo`,
|
||||
`3mo`, `6mo`, `1y`, `5y`. Default: `1mo`.
|
||||
|
||||
### `compare SYMBOL1 SYMBOL2 [...]`
|
||||
|
||||
Side-by-side: price, change%, 52-week performance.
|
||||
|
||||
### `crypto SYMBOL [SYMBOL2 ...]`
|
||||
|
||||
Crypto prices. Pass `BTC` (the script appends `-USD` automatically).
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Yahoo Finance's API is unofficial. Endpoints can change or rate-limit
|
||||
without notice — if requests start failing, that's why.
|
||||
- `market_cap` and `pe_ratio` may return null on `quote` when Yahoo's
|
||||
crumb session isn't established. Set `ALPHA_VANTAGE_KEY` to backfill.
|
||||
- Add a small delay between bulk requests to avoid rate-limiting.
|
||||
- This is read-only — no order placement, no account integration.
|
||||
|
||||
## Verification
|
||||
|
||||
```
|
||||
python ~/.hermes/skills/finance/stocks/scripts/stocks_client.py quote AAPL
|
||||
```
|
||||
|
||||
Returns a JSON object with `symbol: "AAPL"` and a numeric `price` field.
|
||||
@@ -0,0 +1,209 @@
|
||||
---
|
||||
title: "Minecraft Modpack Server — Host modded Minecraft servers (CurseForge, Modrinth)"
|
||||
sidebar_label: "Minecraft Modpack Server"
|
||||
description: "Host modded Minecraft servers (CurseForge, Modrinth)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Minecraft Modpack Server
|
||||
|
||||
Host modded Minecraft servers (CurseForge, Modrinth).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/gaming/minecraft-modpack-server` |
|
||||
| Path | `optional-skills/gaming\minecraft-modpack-server` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Teknium (teknium1), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Minecraft Modpack Server Setup
|
||||
|
||||
## When to use
|
||||
- User wants to set up a modded Minecraft server from a server pack zip
|
||||
- User needs help with NeoForge/Forge server configuration
|
||||
- User asks about Minecraft server performance tuning or backups
|
||||
|
||||
## Gather User Preferences First
|
||||
Before starting setup, ask the user for:
|
||||
- **Server name / MOTD** — what should it say in the server list?
|
||||
- **Seed** — specific seed or random?
|
||||
- **Difficulty** — peaceful / easy / normal / hard?
|
||||
- **Gamemode** — survival / creative / adventure?
|
||||
- **Online mode** — true (Mojang auth, legit accounts) or false (LAN/cracked friendly)?
|
||||
- **Player count** — how many players expected? (affects RAM & view distance tuning)
|
||||
- **RAM allocation** — or let agent decide based on mod count & available RAM?
|
||||
- **View distance / simulation distance** — or let agent pick based on player count & hardware?
|
||||
- **PvP** — on or off?
|
||||
- **Whitelist** — open server or whitelist only?
|
||||
- **Backups** — want automated backups? How often?
|
||||
|
||||
Use sensible defaults if the user doesn't care, but always ask before generating the config.
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Download & Inspect the Pack
|
||||
```bash
|
||||
mkdir -p ~/minecraft-server
|
||||
cd ~/minecraft-server
|
||||
wget -O serverpack.zip "<URL>"
|
||||
unzip -o serverpack.zip -d server
|
||||
ls server/
|
||||
```
|
||||
Look for: `startserver.sh`, installer jar (neoforge/forge), `user_jvm_args.txt`, `mods/` folder.
|
||||
Check the script to determine: mod loader type, version, and required Java version.
|
||||
|
||||
### 2. Install Java
|
||||
- Minecraft 1.21+ → Java 21: `sudo apt install openjdk-21-jre-headless`
|
||||
- Minecraft 1.18-1.20 → Java 17: `sudo apt install openjdk-17-jre-headless`
|
||||
- Minecraft 1.16 and below → Java 8: `sudo apt install openjdk-8-jre-headless`
|
||||
- Verify: `java -version`
|
||||
|
||||
### 3. Install the Mod Loader
|
||||
Most server packs include an install script. Use the INSTALL_ONLY env var to install without launching:
|
||||
```bash
|
||||
cd ~/minecraft-server/server
|
||||
ATM10_INSTALL_ONLY=true bash startserver.sh
|
||||
# Or for generic Forge packs:
|
||||
# java -jar forge-*-installer.jar --installServer
|
||||
```
|
||||
This downloads libraries, patches the server jar, etc.
|
||||
|
||||
### 4. Accept EULA
|
||||
```bash
|
||||
echo "eula=true" > ~/minecraft-server/server/eula.txt
|
||||
```
|
||||
|
||||
### 5. Configure server.properties
|
||||
Key settings for modded/LAN:
|
||||
```properties
|
||||
motd=\u00a7b\u00a7lServer Name \u00a7r\u00a78| \u00a7aModpack Name
|
||||
server-port=25565
|
||||
online-mode=true # false for LAN without Mojang auth
|
||||
enforce-secure-profile=true # match online-mode
|
||||
difficulty=hard # most modpacks balance around hard
|
||||
allow-flight=true # REQUIRED for modded (flying mounts/items)
|
||||
spawn-protection=0 # let everyone build at spawn
|
||||
max-tick-time=180000 # modded needs longer tick timeout
|
||||
enable-command-block=true
|
||||
```
|
||||
|
||||
Performance settings (scale to hardware):
|
||||
```properties
|
||||
# 2 players, beefy machine:
|
||||
view-distance=16
|
||||
simulation-distance=10
|
||||
|
||||
# 4-6 players, moderate machine:
|
||||
view-distance=10
|
||||
simulation-distance=6
|
||||
|
||||
# 8+ players or weaker hardware:
|
||||
view-distance=8
|
||||
simulation-distance=4
|
||||
```
|
||||
|
||||
### 6. Tune JVM Args (user_jvm_args.txt)
|
||||
Scale RAM to player count and mod count. Rule of thumb for modded:
|
||||
- 100-200 mods: 6-12GB
|
||||
- 200-350+ mods: 12-24GB
|
||||
- Leave at least 8GB free for the OS/other tasks
|
||||
|
||||
```
|
||||
-Xms12G
|
||||
-Xmx24G
|
||||
-XX:+UseG1GC
|
||||
-XX:+ParallelRefProcEnabled
|
||||
-XX:MaxGCPauseMillis=200
|
||||
-XX:+UnlockExperimentalVMOptions
|
||||
-XX:+DisableExplicitGC
|
||||
-XX:+AlwaysPreTouch
|
||||
-XX:G1NewSizePercent=30
|
||||
-XX:G1MaxNewSizePercent=40
|
||||
-XX:G1HeapRegionSize=8M
|
||||
-XX:G1ReservePercent=20
|
||||
-XX:G1HeapWastePercent=5
|
||||
-XX:G1MixedGCCountTarget=4
|
||||
-XX:InitiatingHeapOccupancyPercent=15
|
||||
-XX:G1MixedGCLiveThresholdPercent=90
|
||||
-XX:G1RSetUpdatingPauseTimePercent=5
|
||||
-XX:SurvivorRatio=32
|
||||
-XX:+PerfDisableSharedMem
|
||||
-XX:MaxTenuringThreshold=1
|
||||
```
|
||||
|
||||
### 7. Open Firewall
|
||||
```bash
|
||||
sudo ufw allow 25565/tcp comment "Minecraft Server"
|
||||
```
|
||||
Check with: `sudo ufw status | grep 25565`
|
||||
|
||||
### 8. Create Launch Script
|
||||
```bash
|
||||
cat > ~/start-minecraft.sh << 'EOF'
|
||||
#!/bin/bash
|
||||
cd ~/minecraft-server/server
|
||||
java @user_jvm_args.txt @libraries/net/neoforged/neoforge/<VERSION>/unix_args.txt nogui
|
||||
EOF
|
||||
chmod +x ~/start-minecraft.sh
|
||||
```
|
||||
Note: For Forge (not NeoForge), the args file path differs. Check `startserver.sh` for the exact path.
|
||||
|
||||
### 9. Set Up Automated Backups
|
||||
Create backup script:
|
||||
```bash
|
||||
cat > ~/minecraft-server/backup.sh << 'SCRIPT'
|
||||
#!/bin/bash
|
||||
SERVER_DIR="$HOME/minecraft-server/server"
|
||||
BACKUP_DIR="$HOME/minecraft-server/backups"
|
||||
WORLD_DIR="$SERVER_DIR/world"
|
||||
MAX_BACKUPS=24
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
[ ! -d "$WORLD_DIR" ] && echo "[BACKUP] No world folder" && exit 0
|
||||
TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)
|
||||
BACKUP_FILE="$BACKUP_DIR/world_${TIMESTAMP}.tar.gz"
|
||||
echo "[BACKUP] Starting at $(date)"
|
||||
tar -czf "$BACKUP_FILE" -C "$SERVER_DIR" world
|
||||
SIZE=$(du -h "$BACKUP_FILE" | cut -f1)
|
||||
echo "[BACKUP] Saved: $BACKUP_FILE ($SIZE)"
|
||||
BACKUP_COUNT=$(ls -1t "$BACKUP_DIR"/world_*.tar.gz 2>/dev/null | wc -l)
|
||||
if [ "$BACKUP_COUNT" -gt "$MAX_BACKUPS" ]; then
|
||||
REMOVE=$((BACKUP_COUNT - MAX_BACKUPS))
|
||||
ls -1t "$BACKUP_DIR"/world_*.tar.gz | tail -n "$REMOVE" | xargs rm -f
|
||||
echo "[BACKUP] Pruned $REMOVE old backup(s)"
|
||||
fi
|
||||
echo "[BACKUP] Done at $(date)"
|
||||
SCRIPT
|
||||
chmod +x ~/minecraft-server/backup.sh
|
||||
```
|
||||
|
||||
Add hourly cron:
|
||||
```bash
|
||||
(crontab -l 2>/dev/null | grep -v "minecraft/backup.sh"; echo "0 * * * * $HOME/minecraft-server/backup.sh >> $HOME/minecraft-server/backups/backup.log 2>&1") | crontab -
|
||||
```
|
||||
|
||||
## Pitfalls
|
||||
- ALWAYS set `allow-flight=true` for modded — mods with jetpacks/flight will kick players otherwise
|
||||
- `max-tick-time=180000` or higher — modded servers often have long ticks during worldgen
|
||||
- First startup is SLOW (several minutes for big packs) — don't panic
|
||||
- "Can't keep up!" warnings on first launch are normal, settles after initial chunk gen
|
||||
- If online-mode=false, set enforce-secure-profile=false too or clients get rejected
|
||||
- The pack's startserver.sh often has an auto-restart loop — make a clean launch script without it
|
||||
- Delete the world/ folder to regenerate with a new seed
|
||||
- Some packs have env vars to control behavior (e.g., ATM10 uses ATM10_JAVA, ATM10_RESTART, ATM10_INSTALL_ONLY)
|
||||
|
||||
## Verification
|
||||
- `pgrep -fa neoforge` or `pgrep -fa minecraft` to check if running
|
||||
- Check logs: `tail -f ~/minecraft-server/server/logs/latest.log`
|
||||
- Look for "Done (Xs)!" in the log = server is ready
|
||||
- Test connection: player adds server IP in Multiplayer
|
||||
@@ -0,0 +1,240 @@
|
||||
---
|
||||
title: "Pokemon Player — Play Pokemon via headless emulator + RAM reads"
|
||||
sidebar_label: "Pokemon Player"
|
||||
description: "Play Pokemon via headless emulator + RAM reads"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Pokemon Player
|
||||
|
||||
Play Pokemon via headless emulator + RAM reads.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/gaming/pokemon-player` |
|
||||
| Path | `optional-skills/gaming\pokemon-player` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Teknium (teknium1), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Pokemon Player
|
||||
|
||||
Play Pokemon games via headless emulation using the `pokemon-agent` package.
|
||||
|
||||
## When to Use
|
||||
- User says "play pokemon", "start pokemon", "pokemon game"
|
||||
- User asks about Pokemon Red, Blue, Yellow, FireRed, etc.
|
||||
- User wants to watch an AI play Pokemon
|
||||
- User references a ROM file (.gb, .gbc, .gba)
|
||||
|
||||
## Startup Procedure
|
||||
|
||||
### 1. First-time setup (clone, venv, install)
|
||||
The repo is NousResearch/pokemon-agent on GitHub. Clone it, then
|
||||
set up a Python 3.10+ virtual environment. Use uv (preferred for speed)
|
||||
to create the venv and install the package in editable mode with the
|
||||
pyboy extra. If uv is not available, fall back to python -m venv + pip.
|
||||
|
||||
If a checkout already exists (e.g. ~/pokemon-agent with a venv ready),
|
||||
just cd there and source .venv/bin/activate instead of recloning.
|
||||
|
||||
You also need a ROM file. Ask the user for theirs (a previous setup may
|
||||
already have one at roms/pokemon_red.gb inside the checkout).
|
||||
NEVER download or provide ROM files — always ask the user.
|
||||
|
||||
### 2. Start the game server
|
||||
From inside the pokemon-agent directory with the venv activated, run
|
||||
pokemon-agent serve with --rom pointing to the ROM and --port 9876.
|
||||
Run it in the background with &.
|
||||
To resume from a saved game, add --load-state with the save name.
|
||||
Wait 4 seconds for startup, then verify with GET /health.
|
||||
|
||||
### 3. Set up live dashboard for user to watch
|
||||
Use an SSH reverse tunnel via localhost.run so the user can view
|
||||
the dashboard in their browser. Connect with ssh, forwarding local
|
||||
port 9876 to remote port 80 on the keyless localhost.run endpoint
|
||||
(ssh -R 80:localhost:9876 ssh://nokey@localhost.run). Redirect output
|
||||
to a log file, wait 10 seconds, then grep the log for the .lhr.life
|
||||
URL. Give the user the URL with /dashboard/ appended.
|
||||
The tunnel URL changes each time — give the user the new one if restarted.
|
||||
|
||||
## Save and Load
|
||||
|
||||
### When to save
|
||||
- Every 15-20 turns of gameplay
|
||||
- ALWAYS before gym battles, rival encounters, or risky fights
|
||||
- Before entering a new town or dungeon
|
||||
- Before any action you are unsure about
|
||||
|
||||
### How to save
|
||||
POST /save with a descriptive name. Good examples:
|
||||
before_brock, route1_start, mt_moon_entrance, got_cut
|
||||
|
||||
### How to load
|
||||
POST /load with the save name.
|
||||
|
||||
### List available saves
|
||||
GET /saves returns all saved states.
|
||||
|
||||
### Loading on server startup
|
||||
Use --load-state flag when starting the server to auto-load a save.
|
||||
This is faster than loading via the API after startup.
|
||||
|
||||
## The Gameplay Loop
|
||||
|
||||
### Step 1: OBSERVE — check state AND take a screenshot
|
||||
GET /state for position, HP, battle, dialog.
|
||||
GET /screenshot and save to /tmp/pokemon.png, then use vision_analyze.
|
||||
Always do BOTH — RAM state gives numbers, vision gives spatial awareness.
|
||||
|
||||
### Step 2: ORIENT
|
||||
- Dialog/text on screen → advance it
|
||||
- In battle → fight or run
|
||||
- Party hurt → head to Pokemon Center
|
||||
- Near objective → navigate carefully
|
||||
|
||||
### Step 3: DECIDE
|
||||
Priority: dialog > battle > heal > story objective > training > explore
|
||||
|
||||
### Step 4: ACT — move 2-4 steps max, then re-check
|
||||
POST /action with a SHORT action list (2-4 actions, not 10-15).
|
||||
|
||||
### Step 5: VERIFY — screenshot after every move sequence
|
||||
Take a screenshot and use vision_analyze to confirm you moved where
|
||||
intended. This is the MOST IMPORTANT step. Without vision you WILL get lost.
|
||||
|
||||
### Step 6: RECORD progress to memory with PKM: prefix
|
||||
|
||||
### Step 7: SAVE periodically
|
||||
|
||||
## Action Reference
|
||||
- press_a — confirm, talk, select
|
||||
- press_b — cancel, close menu
|
||||
- press_start — open game menu
|
||||
- walk_up/down/left/right — move one tile
|
||||
- hold_b_N — hold B for N frames (use for speeding through text)
|
||||
- wait_60 — wait about 1 second (60 frames)
|
||||
- a_until_dialog_end — press A repeatedly until dialog clears
|
||||
|
||||
## Critical Tips from Experience
|
||||
|
||||
### USE VISION CONSTANTLY
|
||||
- Take a screenshot every 2-4 movement steps
|
||||
- The RAM state tells you position and HP but NOT what is around you
|
||||
- Ledges, fences, signs, building doors, NPCs — only visible via screenshot
|
||||
- Ask the vision model specific questions: "what is one tile north of me?"
|
||||
- When stuck, always screenshot before trying random directions
|
||||
|
||||
### Warp Transitions Need Extra Wait Time
|
||||
When walking through a door or stairs, the screen fades to black during
|
||||
the map transition. You MUST wait for it to complete. Add 2-3 wait_60
|
||||
actions after any door/stair warp. Without waiting, the position reads
|
||||
as stale and you will think you are still in the old map.
|
||||
|
||||
### Building Exit Trap
|
||||
When you exit a building, you appear directly IN FRONT of the door.
|
||||
If you walk north, you go right back inside. ALWAYS sidestep first
|
||||
by walking left or right 2 tiles, then proceed in your intended direction.
|
||||
|
||||
### Dialog Handling
|
||||
Gen 1 text scrolls slowly letter-by-letter. To speed through dialog,
|
||||
hold B for 120 frames then press A. Repeat as needed. Holding B makes
|
||||
text display at max speed. Then press A to advance to the next line.
|
||||
The a_until_dialog_end action checks the RAM dialog flag, but this flag
|
||||
does not catch ALL text states. If dialog seems stuck, use the manual
|
||||
hold_b + press_a pattern instead and verify via screenshot.
|
||||
|
||||
### Ledges Are One-Way
|
||||
Ledges (small cliff edges) can only be jumped DOWN (south), never climbed
|
||||
UP (north). If blocked by a ledge going north, you must go left or right
|
||||
to find the gap around it. Use vision to identify which direction the
|
||||
gap is. Ask the vision model explicitly.
|
||||
|
||||
### Navigation Strategy
|
||||
- Move 2-4 steps at a time, then screenshot to check position
|
||||
- When entering a new area, screenshot immediately to orient
|
||||
- Ask the vision model "which direction to [destination]?"
|
||||
- If stuck for 3+ attempts, screenshot and re-evaluate completely
|
||||
- Do not spam 10-15 movements — you will overshoot or get stuck
|
||||
|
||||
### Running from Wild Battles
|
||||
On the battle menu, RUN is bottom-right. To reach it from the default
|
||||
cursor position (FIGHT, top-left): press down then right to move cursor
|
||||
to RUN, then press A. Wrap with hold_b to speed through text/animations.
|
||||
|
||||
### Battling (FIGHT)
|
||||
On the battle menu FIGHT is top-left (default cursor position).
|
||||
Press A to enter move selection, A again to use the first move.
|
||||
Then hold B to speed through attack animations and text.
|
||||
|
||||
## Battle Strategy
|
||||
|
||||
### Decision Tree
|
||||
1. Want to catch? → Weaken then throw Poke Ball
|
||||
2. Wild you don't need? → RUN
|
||||
3. Type advantage? → Use super-effective move
|
||||
4. No advantage? → Use strongest STAB move
|
||||
5. Low HP? → Switch or use Potion
|
||||
|
||||
### Gen 1 Type Chart (key matchups)
|
||||
- Water beats Fire, Ground, Rock
|
||||
- Fire beats Grass, Bug, Ice
|
||||
- Grass beats Water, Ground, Rock
|
||||
- Electric beats Water, Flying
|
||||
- Ground beats Fire, Electric, Rock, Poison
|
||||
- Psychic beats Fighting, Poison (dominant in Gen 1!)
|
||||
|
||||
### Gen 1 Quirks
|
||||
- Special stat = both offense AND defense for special moves
|
||||
- Psychic type is overpowered (Ghost moves bugged)
|
||||
- Critical hits based on Speed stat
|
||||
- Wrap/Bind prevent opponent from acting
|
||||
- Focus Energy bug: REDUCES crit rate instead of raising it
|
||||
|
||||
## Memory Conventions
|
||||
| Prefix | Purpose | Example |
|
||||
|--------|---------|---------|
|
||||
| PKM:OBJECTIVE | Current goal | Get Parcel from Viridian Mart |
|
||||
| PKM:MAP | Navigation knowledge | Viridian: mart is northeast |
|
||||
| PKM:STRATEGY | Battle/team plans | Need Grass type before Misty |
|
||||
| PKM:PROGRESS | Milestone tracker | Beat rival, heading to Viridian |
|
||||
| PKM:STUCK | Stuck situations | Ledge at y=28 go right to bypass |
|
||||
| PKM:TEAM | Team notes | Squirtle Lv6, Tackle + Tail Whip |
|
||||
|
||||
## Progression Milestones
|
||||
- Choose starter
|
||||
- Deliver Parcel from Viridian Mart, receive Pokedex
|
||||
- Boulder Badge — Brock (Rock) → use Water/Grass
|
||||
- Cascade Badge — Misty (Water) → use Grass/Electric
|
||||
- Thunder Badge — Lt. Surge (Electric) → use Ground
|
||||
- Rainbow Badge — Erika (Grass) → use Fire/Ice/Flying
|
||||
- Soul Badge — Koga (Poison) → use Ground/Psychic
|
||||
- Marsh Badge — Sabrina (Psychic) → hardest gym
|
||||
- Volcano Badge — Blaine (Fire) → use Water/Ground
|
||||
- Earth Badge — Giovanni (Ground) → use Water/Grass/Ice
|
||||
- Elite Four → Champion!
|
||||
|
||||
## Stopping Play
|
||||
1. Save the game with a descriptive name via POST /save
|
||||
2. Update memory with PKM:PROGRESS
|
||||
3. Tell user: "Game saved as [name]! Say 'play pokemon' to resume."
|
||||
4. Kill the server and tunnel background processes
|
||||
|
||||
## Pitfalls
|
||||
- NEVER download or provide ROM files
|
||||
- Do NOT send more than 4-5 actions without checking vision
|
||||
- Always sidestep after exiting buildings before going north
|
||||
- Always add wait_60 x2-3 after door/stair warps
|
||||
- Dialog detection via RAM is unreliable — verify with screenshots
|
||||
- Save BEFORE risky encounters
|
||||
- The tunnel URL changes each time you restart it
|
||||
@@ -0,0 +1,259 @@
|
||||
---
|
||||
title: "Fitness Nutrition — Workout planning, macros, and body metrics via wger/USDA"
|
||||
sidebar_label: "Fitness Nutrition"
|
||||
description: "Workout planning, macros, and body metrics via wger/USDA"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Fitness Nutrition
|
||||
|
||||
Workout planning, macros, and body metrics via wger/USDA.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/health/fitness-nutrition` |
|
||||
| Path | `optional-skills/health\fitness-nutrition` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hailey Marshall (haileymarshall), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `health`, `fitness`, `nutrition`, `gym`, `workout`, `diet`, `exercise` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Fitness & Nutrition
|
||||
|
||||
Expert fitness coach and sports nutritionist skill. Two data sources
|
||||
plus offline calculators — everything a gym-goer needs in one place.
|
||||
|
||||
**Data sources (all free, no pip dependencies):**
|
||||
|
||||
- **wger** (https://wger.de/api/v2/) — open exercise database, 690+ exercises with muscles, equipment, images. Public endpoints need zero authentication.
|
||||
- **USDA FoodData Central** (https://api.nal.usda.gov/fdc/v1/) — US government nutrition database, 380,000+ foods. `DEMO_KEY` works instantly; free signup for higher limits.
|
||||
|
||||
**Offline calculators (pure stdlib Python):**
|
||||
|
||||
- BMI, TDEE (Mifflin-St Jeor), one-rep max (Epley/Brzycki/Lombardi), macro splits, body fat % (US Navy method)
|
||||
|
||||
---
|
||||
|
||||
## When to Use
|
||||
|
||||
Trigger this skill when the user asks about:
|
||||
- Exercises, workouts, gym routines, muscle groups, workout splits
|
||||
- Food macros, calories, protein content, meal planning, calorie counting
|
||||
- Body composition: BMI, body fat, TDEE, caloric surplus/deficit
|
||||
- One-rep max estimates, training percentages, progressive overload
|
||||
- Macro ratios for cutting, bulking, or maintenance
|
||||
|
||||
---
|
||||
|
||||
## Procedure
|
||||
|
||||
### Exercise Lookup (wger API)
|
||||
|
||||
All wger public endpoints return JSON and require no auth. Always add
|
||||
`format=json` and `language=2` (English) to exercise queries.
|
||||
|
||||
**Step 1 — Identify what the user wants:**
|
||||
|
||||
- By muscle → use `/api/v2/exercise/?muscles={id}&language=2&status=2&format=json`
|
||||
- By category → use `/api/v2/exercise/?category={id}&language=2&status=2&format=json`
|
||||
- By equipment → use `/api/v2/exercise/?equipment={id}&language=2&status=2&format=json`
|
||||
- By name → use `/api/v2/exercise/search/?term={query}&language=english&format=json`
|
||||
- Full details → use `/api/v2/exerciseinfo/{exercise_id}/?format=json`
|
||||
|
||||
**Step 2 — Reference IDs (so you don't need extra API calls):**
|
||||
|
||||
Exercise categories:
|
||||
|
||||
| ID | Category |
|
||||
|----|-------------|
|
||||
| 8 | Arms |
|
||||
| 9 | Legs |
|
||||
| 10 | Abs |
|
||||
| 11 | Chest |
|
||||
| 12 | Back |
|
||||
| 13 | Shoulders |
|
||||
| 14 | Calves |
|
||||
| 15 | Cardio |
|
||||
|
||||
Muscles:
|
||||
|
||||
| ID | Muscle | ID | Muscle |
|
||||
|----|---------------------------|----|-------------------------|
|
||||
| 1 | Biceps brachii | 2 | Anterior deltoid |
|
||||
| 3 | Serratus anterior | 4 | Pectoralis major |
|
||||
| 5 | Obliquus externus | 6 | Gastrocnemius |
|
||||
| 7 | Rectus abdominis | 8 | Gluteus maximus |
|
||||
| 9 | Trapezius | 10 | Quadriceps femoris |
|
||||
| 11 | Biceps femoris | 12 | Latissimus dorsi |
|
||||
| 13 | Brachialis | 14 | Triceps brachii |
|
||||
| 15 | Soleus | | |
|
||||
|
||||
Equipment:
|
||||
|
||||
| ID | Equipment |
|
||||
|----|----------------|
|
||||
| 1 | Barbell |
|
||||
| 3 | Dumbbell |
|
||||
| 4 | Gym mat |
|
||||
| 5 | Swiss Ball |
|
||||
| 6 | Pull-up bar |
|
||||
| 7 | none (bodyweight) |
|
||||
| 8 | Bench |
|
||||
| 9 | Incline bench |
|
||||
| 10 | Kettlebell |
|
||||
|
||||
**Step 3 — Fetch and present results:**
|
||||
|
||||
```bash
|
||||
# Search exercises by name
|
||||
QUERY="$1"
|
||||
ENCODED=$(python -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$QUERY")
|
||||
curl -s "https://wger.de/api/v2/exercise/search/?term=${ENCODED}&language=english&format=json" \
|
||||
| python -c "
|
||||
import json,sys
|
||||
data=json.load(sys.stdin)
|
||||
for s in data.get('suggestions',[])[:10]:
|
||||
d=s.get('data',{})
|
||||
print(f\" ID {d.get('id','?'):>4} | {d.get('name','N/A'):<35} | Category: {d.get('category','N/A')}\")
|
||||
"
|
||||
```
|
||||
|
||||
```bash
|
||||
# Get full details for a specific exercise
|
||||
EXERCISE_ID="$1"
|
||||
curl -s "https://wger.de/api/v2/exerciseinfo/${EXERCISE_ID}/?format=json" \
|
||||
| python -c "
|
||||
import json,sys,html,re
|
||||
data=json.load(sys.stdin)
|
||||
trans=[t for t in data.get('translations',[]) if t.get('language')==2]
|
||||
t=trans[0] if trans else data.get('translations',[{}])[0]
|
||||
desc=re.sub('<[^>]+>','',html.unescape(t.get('description','N/A')))
|
||||
print(f\"Exercise : {t.get('name','N/A')}\")
|
||||
print(f\"Category : {data.get('category',{}).get('name','N/A')}\")
|
||||
print(f\"Primary : {', '.join(m.get('name_en','') for m in data.get('muscles',[])) or 'N/A'}\")
|
||||
print(f\"Secondary : {', '.join(m.get('name_en','') for m in data.get('muscles_secondary',[])) or 'none'}\")
|
||||
print(f\"Equipment : {', '.join(e.get('name','') for e in data.get('equipment',[])) or 'bodyweight'}\")
|
||||
print(f\"How to : {desc[:500]}\")
|
||||
imgs=data.get('images',[])
|
||||
if imgs: print(f\"Image : {imgs[0].get('image','')}\")
|
||||
"
|
||||
```
|
||||
|
||||
```bash
|
||||
# List exercises filtering by muscle, category, or equipment
|
||||
# Combine filters as needed: ?muscles=4&equipment=1&language=2&status=2
|
||||
FILTER="$1" # e.g. "muscles=4" or "category=11" or "equipment=3"
|
||||
curl -s "https://wger.de/api/v2/exercise/?${FILTER}&language=2&status=2&limit=20&format=json" \
|
||||
| python -c "
|
||||
import json,sys
|
||||
data=json.load(sys.stdin)
|
||||
print(f'Found {data.get(\"count\",0)} exercises.')
|
||||
for ex in data.get('results',[]):
|
||||
print(f\" ID {ex['id']:>4} | muscles: {ex.get('muscles',[])} | equipment: {ex.get('equipment',[])}\")
|
||||
"
|
||||
```
|
||||
|
||||
### Nutrition Lookup (USDA FoodData Central)
|
||||
|
||||
Uses `USDA_API_KEY` env var if set, otherwise falls back to `DEMO_KEY`.
|
||||
DEMO_KEY = 30 requests/hour. Free signup key = 1,000 requests/hour.
|
||||
|
||||
```bash
|
||||
# Search foods by name
|
||||
FOOD="$1"
|
||||
API_KEY="${USDA_API_KEY:-DEMO_KEY}"
|
||||
ENCODED=$(python -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$FOOD")
|
||||
curl -s "https://api.nal.usda.gov/fdc/v1/foods/search?api_key=${API_KEY}&query=${ENCODED}&pageSize=5&dataType=Foundation,SR%20Legacy" \
|
||||
| python -c "
|
||||
import json,sys
|
||||
data=json.load(sys.stdin)
|
||||
foods=data.get('foods',[])
|
||||
if not foods: print('No foods found.'); sys.exit()
|
||||
for f in foods:
|
||||
n={x['nutrientName']:x.get('value','?') for x in f.get('foodNutrients',[])}
|
||||
cal=n.get('Energy','?'); prot=n.get('Protein','?')
|
||||
fat=n.get('Total lipid (fat)','?'); carb=n.get('Carbohydrate, by difference','?')
|
||||
print(f\"{f.get('description','N/A')}\")
|
||||
print(f\" Per 100g: {cal} kcal | {prot}g protein | {fat}g fat | {carb}g carbs\")
|
||||
print(f\" FDC ID: {f.get('fdcId','N/A')}\")
|
||||
print()
|
||||
"
|
||||
```
|
||||
|
||||
```bash
|
||||
# Detailed nutrient profile by FDC ID
|
||||
FDC_ID="$1"
|
||||
API_KEY="${USDA_API_KEY:-DEMO_KEY}"
|
||||
curl -s "https://api.nal.usda.gov/fdc/v1/food/${FDC_ID}?api_key=${API_KEY}" \
|
||||
| python -c "
|
||||
import json,sys
|
||||
d=json.load(sys.stdin)
|
||||
print(f\"Food: {d.get('description','N/A')}\")
|
||||
print(f\"{'Nutrient':<40} {'Amount':>8} {'Unit'}\")
|
||||
print('-'*56)
|
||||
for x in sorted(d.get('foodNutrients',[]),key=lambda x:x.get('nutrient',{}).get('rank',9999)):
|
||||
nut=x.get('nutrient',{}); amt=x.get('amount',0)
|
||||
if amt and float(amt)>0:
|
||||
print(f\" {nut.get('name',''):<38} {amt:>8} {nut.get('unitName','')}\")
|
||||
"
|
||||
```
|
||||
|
||||
### Offline Calculators
|
||||
|
||||
Use the helper scripts in `scripts/` for batch operations,
|
||||
or run inline for single calculations:
|
||||
|
||||
- `python scripts/body_calc.py bmi <weight_kg> <height_cm>`
|
||||
- `python scripts/body_calc.py tdee <weight_kg> <height_cm> <age> <M|F> <activity 1-5>`
|
||||
- `python scripts/body_calc.py 1rm <weight> <reps>`
|
||||
- `python scripts/body_calc.py macros <tdee_kcal> <cut|maintain|bulk>`
|
||||
- `python scripts/body_calc.py bodyfat <M|F> <neck_cm> <waist_cm> [hip_cm] <height_cm>`
|
||||
|
||||
See `references/FORMULAS.md` for the science behind each formula.
|
||||
|
||||
---
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- wger exercise endpoint returns **all languages by default** — always add `language=2` for English
|
||||
- wger includes **unverified user submissions** — add `status=2` to only get approved exercises
|
||||
- USDA `DEMO_KEY` has **30 req/hour** — add `sleep 2` between batch requests or get a free key
|
||||
- USDA data is **per 100g** — remind users to scale to their actual portion size
|
||||
- BMI does not distinguish muscle from fat — high BMI in muscular people is not necessarily unhealthy
|
||||
- Body fat formulas are **estimates** (±3-5%) — recommend DEXA scans for precision
|
||||
- 1RM formulas lose accuracy above 10 reps — use sets of 3-5 for best estimates
|
||||
- wger's `exercise/search` endpoint uses `term` not `query` as the parameter name
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
After running exercise search: confirm results include exercise names, muscle groups, and equipment.
|
||||
After nutrition lookup: confirm per-100g macros are returned with kcal, protein, fat, carbs.
|
||||
After calculators: sanity-check outputs (e.g. TDEE should be 1500-3500 for most adults).
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Task | Source | Endpoint |
|
||||
|------|--------|----------|
|
||||
| Search exercises by name | wger | `GET /api/v2/exercise/search/?term=&language=english` |
|
||||
| Exercise details | wger | `GET /api/v2/exerciseinfo/{id}/` |
|
||||
| Filter by muscle | wger | `GET /api/v2/exercise/?muscles={id}&language=2&status=2` |
|
||||
| Filter by equipment | wger | `GET /api/v2/exercise/?equipment={id}&language=2&status=2` |
|
||||
| List categories | wger | `GET /api/v2/exercisecategory/` |
|
||||
| List muscles | wger | `GET /api/v2/muscle/` |
|
||||
| Search foods | USDA | `GET /fdc/v1/foods/search?query=&dataType=Foundation,SR Legacy` |
|
||||
| Food details | USDA | `GET /fdc/v1/food/{fdcId}` |
|
||||
| BMI / TDEE / 1RM / macros | offline | `python scripts/body_calc.py` |
|
||||
@@ -0,0 +1,470 @@
|
||||
---
|
||||
title: "Neuroskill Bci — Use live BCI cognitive and mood state from NeuroSkill"
|
||||
sidebar_label: "Neuroskill Bci"
|
||||
description: "Use live BCI cognitive and mood state from NeuroSkill"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Neuroskill Bci
|
||||
|
||||
Use live BCI cognitive and mood state from NeuroSkill.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/health/neuroskill-bci` |
|
||||
| Path | `optional-skills/health\neuroskill-bci` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hermes Agent + Nous Research |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `BCI`, `neurofeedback`, `health`, `focus`, `EEG`, `cognitive-state`, `biometrics`, `neuroskill` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# NeuroSkill BCI Integration
|
||||
|
||||
Connect Hermes to a running [NeuroSkill](https://neuroskill.com/) instance to read
|
||||
real-time brain and body metrics from a BCI wearable. Use this to give
|
||||
cognitively-aware responses, suggest interventions, and track mental performance
|
||||
over time.
|
||||
|
||||
> **⚠️ Research Use Only** — NeuroSkill is an open-source research tool. It is
|
||||
> NOT a medical device and has NOT been cleared by the FDA, CE, or any regulatory
|
||||
> body. Never use these metrics for clinical diagnosis or treatment.
|
||||
|
||||
See `references/metrics.md` for the full metric reference, `references/protocols.md`
|
||||
for intervention protocols, and `references/api.md` for the WebSocket/HTTP API.
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Node.js 20+** installed (`node --version`)
|
||||
- **NeuroSkill desktop app** running with a connected BCI device
|
||||
- **BCI hardware**: Muse 2, Muse S, or OpenBCI (4-channel EEG + PPG + IMU via BLE)
|
||||
- `npx neuroskill status` returns data without errors
|
||||
|
||||
### Verify Setup
|
||||
```bash
|
||||
node --version # Must be 20+
|
||||
npx neuroskill status # Full system snapshot
|
||||
npx neuroskill status --json # Machine-parseable JSON
|
||||
```
|
||||
|
||||
If `npx neuroskill status` returns an error, tell the user:
|
||||
- Make sure the NeuroSkill desktop app is open
|
||||
- Ensure the BCI device is powered on and connected via Bluetooth
|
||||
- Check signal quality — green indicators in NeuroSkill (≥0.7 per electrode)
|
||||
- If `command not found`, install Node.js 20+
|
||||
|
||||
---
|
||||
|
||||
## CLI Reference: `npx neuroskill <command>`
|
||||
|
||||
All commands support `--json` (raw JSON, pipe-safe) and `--full` (human summary + JSON).
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `status` | Full system snapshot: device, scores, bands, ratios, sleep, history |
|
||||
| `session [N]` | Single session breakdown with first/second half trends (0=most recent) |
|
||||
| `sessions` | List all recorded sessions across all days |
|
||||
| `search` | ANN similarity search for neurally similar historical moments |
|
||||
| `compare` | A/B session comparison with metric deltas and trend analysis |
|
||||
| `sleep [N]` | Sleep stage classification (Wake/N1/N2/N3/REM) with analysis |
|
||||
| `label "text"` | Create a timestamped annotation at the current moment |
|
||||
| `search-labels "query"` | Semantic vector search over past labels |
|
||||
| `interactive "query"` | Cross-modal 4-layer graph search (text → EXG → labels) |
|
||||
| `listen` | Real-time event streaming (default 5s, set `--seconds N`) |
|
||||
| `umap` | 3D UMAP projection of session embeddings |
|
||||
| `calibrate` | Open calibration window and start a profile |
|
||||
| `timer` | Launch focus timer (Pomodoro/Deep Work/Short Focus presets) |
|
||||
| `notify "title" "body"` | Send an OS notification via the NeuroSkill app |
|
||||
| `raw '{json}'` | Raw JSON passthrough to the server |
|
||||
|
||||
### Global Flags
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--json` | Raw JSON output (no ANSI, pipe-safe) |
|
||||
| `--full` | Human summary + colorized JSON |
|
||||
| `--port <N>` | Override server port (default: auto-discover, usually 8375) |
|
||||
| `--ws` | Force WebSocket transport |
|
||||
| `--http` | Force HTTP transport |
|
||||
| `--k <N>` | Nearest neighbors count (search, search-labels) |
|
||||
| `--seconds <N>` | Duration for listen (default: 5) |
|
||||
| `--trends` | Show per-session metric trends (sessions) |
|
||||
| `--dot` | Graphviz DOT output (interactive) |
|
||||
|
||||
---
|
||||
|
||||
## 1. Checking Current State
|
||||
|
||||
### Get Live Metrics
|
||||
```bash
|
||||
npx neuroskill status --json
|
||||
```
|
||||
|
||||
**Always use `--json`** for reliable parsing. The default output is colorized
|
||||
human-readable text.
|
||||
|
||||
### Key Fields in the Response
|
||||
|
||||
The `scores` object contains all live metrics (0–1 scale unless noted):
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"scores": {
|
||||
"focus": 0.70, // β / (α + θ) — sustained attention
|
||||
"relaxation": 0.40, // α / (β + θ) — calm wakefulness
|
||||
"engagement": 0.60, // active mental investment
|
||||
"meditation": 0.52, // alpha + stillness + HRV coherence
|
||||
"mood": 0.55, // composite from FAA, TAR, BAR
|
||||
"cognitive_load": 0.33, // frontal θ / temporal α · f(FAA, TBR)
|
||||
"drowsiness": 0.10, // TAR + TBR + falling spectral centroid
|
||||
"hr": 68.2, // heart rate in bpm (from PPG)
|
||||
"snr": 14.3, // signal-to-noise ratio in dB
|
||||
"stillness": 0.88, // 0–1; 1 = perfectly still
|
||||
"faa": 0.042, // Frontal Alpha Asymmetry (+ = approach)
|
||||
"tar": 0.56, // Theta/Alpha Ratio
|
||||
"bar": 0.53, // Beta/Alpha Ratio
|
||||
"tbr": 1.06, // Theta/Beta Ratio (ADHD proxy)
|
||||
"apf": 10.1, // Alpha Peak Frequency in Hz
|
||||
"coherence": 0.614, // inter-hemispheric coherence
|
||||
"bands": {
|
||||
"rel_delta": 0.28, "rel_theta": 0.18,
|
||||
"rel_alpha": 0.32, "rel_beta": 0.17, "rel_gamma": 0.05
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Also includes: `device` (state, battery, firmware), `signal_quality` (per-electrode 0–1),
|
||||
`session` (duration, epochs), `embeddings`, `labels`, `sleep` summary, and `history`.
|
||||
|
||||
### Interpreting the Output
|
||||
|
||||
Parse the JSON and translate metrics into natural language. Never report raw
|
||||
numbers alone — always give them meaning:
|
||||
|
||||
**DO:**
|
||||
> "Your focus is solid right now at 0.70 — that's flow state territory. Heart
|
||||
> rate is steady at 68 bpm and your FAA is positive, which suggests good
|
||||
> approach motivation. Great time to tackle something complex."
|
||||
|
||||
**DON'T:**
|
||||
> "Focus: 0.70, Relaxation: 0.40, HR: 68"
|
||||
|
||||
Key interpretation thresholds (see `references/metrics.md` for the full guide):
|
||||
- **Focus > 0.70** → flow state territory, protect it
|
||||
- **Focus < 0.40** → suggest a break or protocol
|
||||
- **Drowsiness > 0.60** → fatigue warning, micro-sleep risk
|
||||
- **Relaxation < 0.30** → stress intervention needed
|
||||
- **Cognitive Load > 0.70 sustained** → mind dump or break
|
||||
- **TBR > 1.5** → theta-dominant, reduced executive control
|
||||
- **FAA < 0** → withdrawal/negative affect — consider FAA rebalancing
|
||||
- **SNR < 3 dB** → unreliable signal, suggest electrode repositioning
|
||||
|
||||
---
|
||||
|
||||
## 2. Session Analysis
|
||||
|
||||
### Single Session Breakdown
|
||||
```bash
|
||||
npx neuroskill session --json # most recent session
|
||||
npx neuroskill session 1 --json # previous session
|
||||
npx neuroskill session 0 --json | jq '{focus: .metrics.focus, trend: .trends.focus}'
|
||||
```
|
||||
|
||||
Returns full metrics with **first-half vs second-half trends** (`"up"`, `"down"`, `"flat"`).
|
||||
Use this to describe how a session evolved:
|
||||
|
||||
> "Your focus started at 0.64 and climbed to 0.76 by the end — a clear upward trend.
|
||||
> Cognitive load dropped from 0.38 to 0.28, suggesting the task became more automatic
|
||||
> as you settled in."
|
||||
|
||||
### List All Sessions
|
||||
```bash
|
||||
npx neuroskill sessions --json
|
||||
npx neuroskill sessions --trends # show per-session metric trends
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Historical Search
|
||||
|
||||
### Neural Similarity Search
|
||||
```bash
|
||||
npx neuroskill search --json # auto: last session, k=5
|
||||
npx neuroskill search --k 10 --json # 10 nearest neighbors
|
||||
npx neuroskill search --start <UTC> --end <UTC> --json
|
||||
```
|
||||
|
||||
Finds moments in history that are neurally similar using HNSW approximate
|
||||
nearest-neighbor search over 128-D ZUNA embeddings. Returns distance statistics,
|
||||
temporal distribution (hour of day), and top matching days.
|
||||
|
||||
Use this when the user asks:
|
||||
- "When was I last in a state like this?"
|
||||
- "Find my best focus sessions"
|
||||
- "When do I usually crash in the afternoon?"
|
||||
|
||||
### Semantic Label Search
|
||||
```bash
|
||||
npx neuroskill search-labels "deep focus" --k 10 --json
|
||||
npx neuroskill search-labels "stress" --json | jq '[.results[].EXG_metrics.tbr]'
|
||||
```
|
||||
|
||||
Searches label text using vector embeddings (Xenova/bge-small-en-v1.5). Returns
|
||||
matching labels with their associated EXG metrics at the time of labeling.
|
||||
|
||||
### Cross-Modal Graph Search
|
||||
```bash
|
||||
npx neuroskill interactive "deep focus" --json
|
||||
npx neuroskill interactive "deep focus" --dot | dot -Tsvg > graph.svg
|
||||
```
|
||||
|
||||
4-layer graph: query → text labels → EXG points → nearby labels. Use `--k-text`,
|
||||
`--k-EXG`, `--reach <minutes>` to tune.
|
||||
|
||||
---
|
||||
|
||||
## 4. Session Comparison
|
||||
```bash
|
||||
npx neuroskill compare --json # auto: last 2 sessions
|
||||
npx neuroskill compare --a-start <UTC> --a-end <UTC> --b-start <UTC> --b-end <UTC> --json
|
||||
```
|
||||
|
||||
Returns metric deltas with absolute change, percentage change, and direction for
|
||||
~50 metrics. Also includes `insights.improved[]` and `insights.declined[]` arrays,
|
||||
sleep staging for both sessions, and a UMAP job ID.
|
||||
|
||||
Interpret comparisons with context — mention trends, not just deltas:
|
||||
> "Yesterday you had two strong focus blocks (10am and 2pm). Today you've had one
|
||||
> starting around 11am that's still going. Your overall engagement is higher today
|
||||
> but there have been more stress spikes — your stress index jumped 15% and
|
||||
> FAA dipped negative more often."
|
||||
|
||||
```bash
|
||||
# Sort metrics by improvement percentage
|
||||
npx neuroskill compare --json | jq '.insights.deltas | to_entries | sort_by(.value.pct) | reverse'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Sleep Data
|
||||
```bash
|
||||
npx neuroskill sleep --json # last 24 hours
|
||||
npx neuroskill sleep 0 --json # most recent sleep session
|
||||
npx neuroskill sleep --start <UTC> --end <UTC> --json
|
||||
```
|
||||
|
||||
Returns epoch-by-epoch sleep staging (5-second windows) with analysis:
|
||||
- **Stage codes**: 0=Wake, 1=N1, 2=N2, 3=N3 (deep), 4=REM
|
||||
- **Analysis**: efficiency_pct, onset_latency_min, rem_latency_min, bout counts
|
||||
- **Healthy targets**: N3 15–25%, REM 20–25%, efficiency >85%, onset <20 min
|
||||
|
||||
```bash
|
||||
npx neuroskill sleep --json | jq '.summary | {n3: .n3_epochs, rem: .rem_epochs}'
|
||||
npx neuroskill sleep --json | jq '.analysis.efficiency_pct'
|
||||
```
|
||||
|
||||
Use this when the user mentions sleep, tiredness, or recovery.
|
||||
|
||||
---
|
||||
|
||||
## 6. Labeling Moments
|
||||
```bash
|
||||
npx neuroskill label "breakthrough"
|
||||
npx neuroskill label "studying algorithms"
|
||||
npx neuroskill label "post-meditation"
|
||||
npx neuroskill label --json "focus block start" # returns label_id
|
||||
```
|
||||
|
||||
Auto-label moments when:
|
||||
- User reports a breakthrough or insight
|
||||
- User starts a new task type (e.g., "switching to code review")
|
||||
- User completes a significant protocol
|
||||
- User asks you to mark the current moment
|
||||
- A notable state transition occurs (entering/leaving flow)
|
||||
|
||||
Labels are stored in a database and indexed for later retrieval via `search-labels`
|
||||
and `interactive` commands.
|
||||
|
||||
---
|
||||
|
||||
## 7. Real-Time Streaming
|
||||
```bash
|
||||
npx neuroskill listen --seconds 30 --json
|
||||
npx neuroskill listen --seconds 5 --json | jq '[.[] | select(.event == "scores")]'
|
||||
```
|
||||
|
||||
Streams live WebSocket events (EXG, PPG, IMU, scores, labels) for the specified
|
||||
duration. Requires WebSocket connection (not available with `--http`).
|
||||
|
||||
Use this for continuous monitoring scenarios or to observe metric changes in real-time
|
||||
during a protocol.
|
||||
|
||||
---
|
||||
|
||||
## 8. UMAP Visualization
|
||||
```bash
|
||||
npx neuroskill umap --json # auto: last 2 sessions
|
||||
npx neuroskill umap --a-start <UTC> --a-end <UTC> --b-start <UTC> --b-end <UTC> --json
|
||||
```
|
||||
|
||||
GPU-accelerated 3D UMAP projection of ZUNA embeddings. The `separation_score`
|
||||
indicates how neurally distinct two sessions are:
|
||||
- **> 1.5** → Sessions are neurally distinct (different brain states)
|
||||
- **< 0.5** → Similar brain states across both sessions
|
||||
|
||||
---
|
||||
|
||||
## 9. Proactive State Awareness
|
||||
|
||||
### Session Start Check
|
||||
At the beginning of a session, optionally run a status check if the user mentions
|
||||
they're wearing their device or asks about their state:
|
||||
```bash
|
||||
npx neuroskill status --json
|
||||
```
|
||||
|
||||
Inject a brief state summary:
|
||||
> "Quick check-in: focus is building at 0.62, relaxation is good at 0.55, and your
|
||||
> FAA is positive — approach motivation is engaged. Looks like a solid start."
|
||||
|
||||
### When to Proactively Mention State
|
||||
|
||||
Mention cognitive state **only** when:
|
||||
- User explicitly asks ("How am I doing?", "Check my focus")
|
||||
- User reports difficulty concentrating, stress, or fatigue
|
||||
- A critical threshold is crossed (drowsiness > 0.70, focus < 0.30 sustained)
|
||||
- User is about to do something cognitively demanding and asks for readiness
|
||||
|
||||
**Do NOT** interrupt flow state to report metrics. If focus > 0.75, protect the
|
||||
session — silence is the correct response.
|
||||
|
||||
---
|
||||
|
||||
## 10. Suggesting Protocols
|
||||
|
||||
When metrics indicate a need, suggest a protocol from `references/protocols.md`.
|
||||
Always ask before starting — never interrupt flow state:
|
||||
|
||||
> "Your focus has been declining for the past 15 minutes and TBR is climbing past
|
||||
> 1.5 — signs of theta dominance and mental fatigue. Want me to walk you through
|
||||
> a Theta-Beta Neurofeedback Anchor? It's a 90-second exercise that uses rhythmic
|
||||
> counting and breath to suppress theta and lift beta."
|
||||
|
||||
Key triggers:
|
||||
- **Focus < 0.40, TBR > 1.5** → Theta-Beta Neurofeedback Anchor or Box Breathing
|
||||
- **Relaxation < 0.30, stress_index high** → Cardiac Coherence or 4-7-8 Breathing
|
||||
- **Cognitive Load > 0.70 sustained** → Cognitive Load Offload (mind dump)
|
||||
- **Drowsiness > 0.60** → Ultradian Reset or Wake Reset
|
||||
- **FAA < 0 (negative)** → FAA Rebalancing
|
||||
- **Flow State (focus > 0.75, engagement > 0.70)** → Do NOT interrupt
|
||||
- **High stillness + headache_index** → Neck Release Sequence
|
||||
- **Low RMSSD (< 25ms)** → Vagal Toning
|
||||
|
||||
---
|
||||
|
||||
## 11. Additional Tools
|
||||
|
||||
### Focus Timer
|
||||
```bash
|
||||
npx neuroskill timer --json
|
||||
```
|
||||
Launches the Focus Timer window with Pomodoro (25/5), Deep Work (50/10), or
|
||||
Short Focus (15/5) presets.
|
||||
|
||||
### Calibration
|
||||
```bash
|
||||
npx neuroskill calibrate
|
||||
npx neuroskill calibrate --profile "Eyes Open"
|
||||
```
|
||||
Opens the calibration window. Useful when signal quality is poor or the user
|
||||
wants to establish a personalized baseline.
|
||||
|
||||
### OS Notifications
|
||||
```bash
|
||||
npx neuroskill notify "Break Time" "Your focus has been declining for 20 minutes"
|
||||
```
|
||||
|
||||
### Raw JSON Passthrough
|
||||
```bash
|
||||
npx neuroskill raw '{"command":"status"}' --json
|
||||
```
|
||||
For any server command not yet mapped to a CLI subcommand.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Likely Cause | Fix |
|
||||
|-------|-------------|-----|
|
||||
| `npx neuroskill status` hangs | NeuroSkill app not running | Open NeuroSkill desktop app |
|
||||
| `device.state: "disconnected"` | BCI device not connected | Check Bluetooth, device battery |
|
||||
| All scores return 0 | Poor electrode contact | Reposition headband, moisten electrodes |
|
||||
| `signal_quality` values < 0.7 | Loose electrodes | Adjust fit, clean electrode contacts |
|
||||
| SNR < 3 dB | Noisy signal | Minimize head movement, check environment |
|
||||
| `command not found: npx` | Node.js not installed | Install Node.js 20+ |
|
||||
|
||||
---
|
||||
|
||||
## Example Interactions
|
||||
|
||||
**"How am I doing right now?"**
|
||||
```bash
|
||||
npx neuroskill status --json
|
||||
```
|
||||
→ Interpret scores naturally, mentioning focus, relaxation, mood, and any notable
|
||||
ratios (FAA, TBR). Suggest an action only if metrics indicate a need.
|
||||
|
||||
**"I can't concentrate"**
|
||||
```bash
|
||||
npx neuroskill status --json
|
||||
```
|
||||
→ Check if metrics confirm it (high theta, low beta, rising TBR, high drowsiness).
|
||||
→ If confirmed, suggest an appropriate protocol from `references/protocols.md`.
|
||||
→ If metrics look fine, the issue may be motivational rather than neurological.
|
||||
|
||||
**"Compare my focus today vs yesterday"**
|
||||
```bash
|
||||
npx neuroskill compare --json
|
||||
```
|
||||
→ Interpret trends, not just numbers. Mention what improved, what declined, and
|
||||
possible causes.
|
||||
|
||||
**"When was I last in a flow state?"**
|
||||
```bash
|
||||
npx neuroskill search-labels "flow" --json
|
||||
npx neuroskill search --json
|
||||
```
|
||||
→ Report timestamps, associated metrics, and what the user was doing (from labels).
|
||||
|
||||
**"How did I sleep?"**
|
||||
```bash
|
||||
npx neuroskill sleep --json
|
||||
```
|
||||
→ Report sleep architecture (N3%, REM%, efficiency), compare to healthy targets,
|
||||
and note any issues (high wake epochs, low REM).
|
||||
|
||||
**"Mark this moment — I just had a breakthrough"**
|
||||
```bash
|
||||
npx neuroskill label "breakthrough"
|
||||
```
|
||||
→ Confirm label saved. Optionally note the current metrics to remember the state.
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
- [NeuroSkill Paper — arXiv:2603.03212](https://arxiv.org/abs/2603.03212) (Kosmyna & Hauptmann, MIT Media Lab)
|
||||
- [NeuroSkill Desktop App](https://github.com/NeuroSkill-com/skill) (GPLv3)
|
||||
- [NeuroLoop CLI Companion](https://github.com/NeuroSkill-com/neuroloop) (GPLv3)
|
||||
- [MIT Media Lab Project](https://www.media.mit.edu/projects/neuroskill/overview/)
|
||||
@@ -0,0 +1,315 @@
|
||||
---
|
||||
title: "Fastmcp — Build, test, and deploy Python MCP servers"
|
||||
sidebar_label: "Fastmcp"
|
||||
description: "Build, test, and deploy Python MCP servers"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Fastmcp
|
||||
|
||||
Build, test, and deploy Python MCP servers.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mcp/fastmcp` |
|
||||
| Path | `optional-skills/mcp\fastmcp` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `MCP`, `FastMCP`, `Python`, `Tools`, `Resources`, `Prompts`, `Deployment` |
|
||||
| Related skills | [`hermes-agent`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent), [`mcporter`](/docs/user-guide/skills/optional/mcp/mcp-mcporter) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# FastMCP
|
||||
|
||||
Build MCP servers in Python with FastMCP, validate them locally, install them into MCP clients, and deploy them as HTTP endpoints.
|
||||
|
||||
## When to Use
|
||||
|
||||
Use this skill when the task is to:
|
||||
|
||||
- create a new MCP server in Python
|
||||
- wrap an API, database, CLI, or file-processing workflow as MCP tools
|
||||
- expose resources or prompts in addition to tools
|
||||
- smoke-test a server with the FastMCP CLI before wiring it into Hermes or another client
|
||||
- install a server into Claude Code, Claude Desktop, Cursor, or a similar MCP client
|
||||
- prepare a FastMCP server repo for HTTP deployment
|
||||
|
||||
Use `native-mcp` when the server already exists and only needs to be connected to Hermes. Use `mcporter` when the goal is ad-hoc CLI access to an existing MCP server instead of building one.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Install FastMCP in the working environment first:
|
||||
|
||||
```bash
|
||||
pip install fastmcp
|
||||
fastmcp version
|
||||
```
|
||||
|
||||
For the API template, install `httpx` if it is not already present:
|
||||
|
||||
```bash
|
||||
pip install httpx
|
||||
```
|
||||
|
||||
## Included Files
|
||||
|
||||
### Templates
|
||||
|
||||
- `templates/api_wrapper.py` - REST API wrapper with auth header support
|
||||
- `templates/database_server.py` - read-only SQLite query server
|
||||
- `templates/file_processor.py` - text-file inspection and search server
|
||||
|
||||
### Scripts
|
||||
|
||||
- `scripts/scaffold_fastmcp.py` - copy a starter template and replace the server name placeholder
|
||||
|
||||
### References
|
||||
|
||||
- `references/fastmcp-cli.md` - FastMCP CLI workflow, installation targets, and deployment checks
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Pick the Smallest Viable Server Shape
|
||||
|
||||
Choose the narrowest useful surface area first:
|
||||
|
||||
- API wrapper: start with 1-3 high-value endpoints, not the whole API
|
||||
- database server: expose read-only introspection and a constrained query path
|
||||
- file processor: expose deterministic operations with explicit path arguments
|
||||
- prompts/resources: add only when the client needs reusable prompt templates or discoverable documents
|
||||
|
||||
Prefer a thin server with good names, docstrings, and schemas over a large server with vague tools.
|
||||
|
||||
### 2. Scaffold from a Template
|
||||
|
||||
Copy a template directly or use the scaffold helper:
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/mcp/fastmcp/scripts/scaffold_fastmcp.py \
|
||||
--template api_wrapper \
|
||||
--name "Acme API" \
|
||||
--output ./acme_server.py
|
||||
```
|
||||
|
||||
Available templates:
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/mcp/fastmcp/scripts/scaffold_fastmcp.py --list
|
||||
```
|
||||
|
||||
If copying manually, replace `__SERVER_NAME__` with a real server name.
|
||||
|
||||
### 3. Implement Tools First
|
||||
|
||||
Start with `@mcp.tool` functions before adding resources or prompts.
|
||||
|
||||
Rules for tool design:
|
||||
|
||||
- Give every tool a concrete verb-based name
|
||||
- Write docstrings as user-facing tool descriptions
|
||||
- Keep parameters explicit and typed
|
||||
- Return structured JSON-safe data where possible
|
||||
- Validate unsafe inputs early
|
||||
- Prefer read-only behavior by default for first versions
|
||||
|
||||
Good tool examples:
|
||||
|
||||
- `get_customer`
|
||||
- `search_tickets`
|
||||
- `describe_table`
|
||||
- `summarize_text_file`
|
||||
|
||||
Weak tool examples:
|
||||
|
||||
- `run`
|
||||
- `process`
|
||||
- `do_thing`
|
||||
|
||||
### 4. Add Resources and Prompts Only When They Help
|
||||
|
||||
Add `@mcp.resource` when the client benefits from fetching stable read-only content such as schemas, policy docs, or generated reports.
|
||||
|
||||
Add `@mcp.prompt` when the server should provide a reusable prompt template for a known workflow.
|
||||
|
||||
Do not turn every document into a prompt. Prefer:
|
||||
|
||||
- tools for actions
|
||||
- resources for data/document retrieval
|
||||
- prompts for reusable LLM instructions
|
||||
|
||||
### 5. Test the Server Before Integrating It Anywhere
|
||||
|
||||
Use the FastMCP CLI for local validation:
|
||||
|
||||
```bash
|
||||
fastmcp inspect acme_server.py:mcp
|
||||
fastmcp list acme_server.py --json
|
||||
fastmcp call acme_server.py search_resources query=router limit=5 --json
|
||||
```
|
||||
|
||||
For fast iterative debugging, run the server locally:
|
||||
|
||||
```bash
|
||||
fastmcp run acme_server.py:mcp
|
||||
```
|
||||
|
||||
To test HTTP transport locally:
|
||||
|
||||
```bash
|
||||
fastmcp run acme_server.py:mcp --transport http --host 127.0.0.1 --port 8000
|
||||
fastmcp list http://127.0.0.1:8000/mcp --json
|
||||
fastmcp call http://127.0.0.1:8000/mcp search_resources query=router --json
|
||||
```
|
||||
|
||||
Always run at least one real `fastmcp call` against each new tool before claiming the server works.
|
||||
|
||||
### 6. Install into a Client When Local Validation Passes
|
||||
|
||||
FastMCP can register the server with supported MCP clients:
|
||||
|
||||
```bash
|
||||
fastmcp install claude-code acme_server.py
|
||||
fastmcp install claude-desktop acme_server.py
|
||||
fastmcp install cursor acme_server.py -e .
|
||||
```
|
||||
|
||||
Use `fastmcp discover` to inspect named MCP servers already configured on the machine.
|
||||
|
||||
When the goal is Hermes integration, either:
|
||||
|
||||
- configure the server in `~/.hermes/config.yaml` using the `native-mcp` skill, or
|
||||
- keep using FastMCP CLI commands during development until the interface stabilizes
|
||||
|
||||
### 7. Deploy After the Local Contract Is Stable
|
||||
|
||||
For managed hosting, Prefect Horizon is the path FastMCP documents most directly. Before deployment:
|
||||
|
||||
```bash
|
||||
fastmcp inspect acme_server.py:mcp
|
||||
```
|
||||
|
||||
Make sure the repo contains:
|
||||
|
||||
- a Python file with the FastMCP server object
|
||||
- `requirements.txt` or `pyproject.toml`
|
||||
- any environment-variable documentation needed for deployment
|
||||
|
||||
For generic HTTP hosting, validate the HTTP transport locally first, then deploy on any Python-compatible platform that can expose the server port.
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### API Wrapper Pattern
|
||||
|
||||
Use when exposing a REST or HTTP API as MCP tools.
|
||||
|
||||
Recommended first slice:
|
||||
|
||||
- one read path
|
||||
- one list/search path
|
||||
- optional health check
|
||||
|
||||
Implementation notes:
|
||||
|
||||
- keep auth in environment variables, not hardcoded
|
||||
- centralize request logic in one helper
|
||||
- surface API errors with concise context
|
||||
- normalize inconsistent upstream payloads before returning them
|
||||
|
||||
Start from `templates/api_wrapper.py`.
|
||||
|
||||
### Database Pattern
|
||||
|
||||
Use when exposing safe query and inspection capabilities.
|
||||
|
||||
Recommended first slice:
|
||||
|
||||
- `list_tables`
|
||||
- `describe_table`
|
||||
- one constrained read query tool
|
||||
|
||||
Implementation notes:
|
||||
|
||||
- default to read-only DB access
|
||||
- reject non-`SELECT` SQL in early versions
|
||||
- limit row counts
|
||||
- return rows plus column names
|
||||
|
||||
Start from `templates/database_server.py`.
|
||||
|
||||
### File Processor Pattern
|
||||
|
||||
Use when the server needs to inspect or transform files on demand.
|
||||
|
||||
Recommended first slice:
|
||||
|
||||
- summarize file contents
|
||||
- search within files
|
||||
- extract deterministic metadata
|
||||
|
||||
Implementation notes:
|
||||
|
||||
- accept explicit file paths
|
||||
- check for missing files and encoding failures
|
||||
- cap previews and result counts
|
||||
- avoid shelling out unless a specific external tool is required
|
||||
|
||||
Start from `templates/file_processor.py`.
|
||||
|
||||
## Quality Bar
|
||||
|
||||
Before handing off a FastMCP server, verify all of the following:
|
||||
|
||||
- server imports cleanly
|
||||
- `fastmcp inspect <file.py:mcp>` succeeds
|
||||
- `fastmcp list <server spec> --json` succeeds
|
||||
- every new tool has at least one real `fastmcp call`
|
||||
- environment variables are documented
|
||||
- the tool surface is small enough to understand without guesswork
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### FastMCP command missing
|
||||
|
||||
Install the package in the active environment:
|
||||
|
||||
```bash
|
||||
pip install fastmcp
|
||||
fastmcp version
|
||||
```
|
||||
|
||||
### `fastmcp inspect` fails
|
||||
|
||||
Check that:
|
||||
|
||||
- the file imports without side effects that crash
|
||||
- the FastMCP instance is named correctly in `<file.py:object>`
|
||||
- optional dependencies from the template are installed
|
||||
|
||||
### Tool works in Python but not through CLI
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
fastmcp list server.py --json
|
||||
fastmcp call server.py your_tool_name --json
|
||||
```
|
||||
|
||||
This usually exposes naming mismatches, missing required arguments, or non-serializable return values.
|
||||
|
||||
### Hermes cannot see the deployed server
|
||||
|
||||
The server-building part may be correct while the Hermes config is not. Load the `native-mcp` skill and configure the server in `~/.hermes/config.yaml`, then restart Hermes.
|
||||
|
||||
## References
|
||||
|
||||
For CLI details, install targets, and deployment checks, read `references/fastmcp-cli.md`.
|
||||
@@ -0,0 +1,389 @@
|
||||
---
|
||||
title: "Mcp Oauth Remote Gateway — Manual OAuth for remote MCP servers on headless gateways"
|
||||
sidebar_label: "Mcp Oauth Remote Gateway"
|
||||
description: "Manual OAuth for remote MCP servers on headless gateways"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Mcp Oauth Remote Gateway
|
||||
|
||||
Manual OAuth for remote MCP servers on headless gateways.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mcp/mcp-oauth-remote-gateway` |
|
||||
| Path | `optional-skills/mcp\mcp-oauth-remote-gateway` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Ben Barclay (benbarclay), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `MCP`, `OAuth`, `PKCE`, `Remote-Deployment` |
|
||||
| Related skills | [`hermes-agent`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent), [`mcporter`](/docs/user-guide/skills/optional/mcp/mcp-mcporter), [`fastmcp`](/docs/user-guide/skills/optional/mcp/mcp-fastmcp) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# MCP OAuth on a Remote Hermes Gateway
|
||||
|
||||
## Overview
|
||||
|
||||
Hermes' built-in MCP OAuth client runs a one-shot HTTP listener on `127.0.0.1:<port>`
|
||||
inside the Hermes process and registers that loopback address as the OAuth
|
||||
`redirect_uri`. That works perfectly for a local CLI on the user's own machine.
|
||||
It breaks completely when Hermes runs as a remote gateway (container, VPS,
|
||||
messaging bot), because the user's browser resolves `127.0.0.1` to the user's own
|
||||
laptop, not the remote container — so the authorization code never reaches Hermes.
|
||||
|
||||
This skill does the OAuth dance by hand and writes the resulting tokens into the
|
||||
exact files Hermes' token storage expects, so a subsequent `/reload-mcp` finds
|
||||
cached tokens and skips the browser flow entirely.
|
||||
|
||||
## When to Use
|
||||
|
||||
Use this skill when **all** of the following are true:
|
||||
|
||||
1. The user wants to add a remote HTTP MCP server that requires OAuth (not a static Bearer token).
|
||||
2. Hermes is running as a **remote gateway** (container, VPS, Docker, managed service) — NOT a local CLI on the user's laptop.
|
||||
3. The server supports OAuth 2.1 with PKCE and RFC 7591 Dynamic Client Registration (most modern MCP servers do — Better Stack, Linear, Cloudflare, Datadog, etc.). If it doesn't support DCR (GitHub is the notable exception), this skill does not apply — use a pre-registered OAuth App or a Personal Access Token instead.
|
||||
|
||||
Do NOT use this for:
|
||||
- **Local CLI Hermes** — just set `auth: oauth` in `mcp_servers.<name>` and `/reload-mcp`. The built-in flow opens a browser and captures the callback on localhost. Works perfectly.
|
||||
- **Servers that accept a static Bearer token (API key)** — always prefer `headers.Authorization: "Bearer <token>"` when the user is willing. Simpler, no refresh dance.
|
||||
- **GitHub Copilot MCP** (`api.githubcopilot.com/mcp/`) — GitHub does not expose DCR. Use a PAT or a pre-registered OAuth App (see pitfall 12).
|
||||
|
||||
## Why the Built-in OAuth Flow Fails on a Remote Gateway
|
||||
|
||||
Hermes' native MCP OAuth client (`tools/mcp_oauth.py`):
|
||||
|
||||
1. Picks a free local port `P`.
|
||||
2. Registers a dynamic OAuth client with the AS, sending `redirect_uri = http://127.0.0.1:P/callback`.
|
||||
3. Starts an HTTP server on `127.0.0.1:P` **inside the Hermes process**.
|
||||
4. Prints the authorize URL and waits for the code at its local endpoint.
|
||||
|
||||
When Hermes runs remotely, the `127.0.0.1` in the `redirect_uri` is the remote
|
||||
container's loopback, not the user's. After authorizing, the user's browser 302s
|
||||
to `http://127.0.0.1:P/callback?code=...`, which resolves to the user's own
|
||||
laptop and fails to connect. The callback never reaches the Hermes process, the
|
||||
flow times out, and `/reload-mcp` returns "No MCP tools available" with no detail.
|
||||
|
||||
Symptoms to recognize: `[xdg-open] <defunct>` processes under the hermes user, an
|
||||
empty or missing tokens directory (`$HERMES_HOME/mcp-tokens/`), and a reload that
|
||||
responds without any "Added/Reconnected: X" line in `change_detail`.
|
||||
|
||||
## Cheap First Fallbacks: the Built-in Flow's Own Escape Hatches
|
||||
|
||||
Before any manual token surgery, check whether the built-in flow's fallbacks
|
||||
already cover the deployment. When Hermes detects a remote session it prints two
|
||||
options alongside the authorize URL (`tools/mcp_oauth.py`):
|
||||
|
||||
1. **Paste-back** — on an interactive TTY, a stdin reader races the HTTP
|
||||
listener. The user authorizes, the browser fails to connect to
|
||||
`127.0.0.1:<port>`, and they paste the full address-bar URL
|
||||
(`?code=...&state=...`) back at the prompt. Works for SSH'd-in CLI sessions.
|
||||
2. **SSH port-forward** — `ssh -N -L <port>:127.0.0.1:<port> <user>@<host>`
|
||||
makes the redirect reach the remote listener normally.
|
||||
|
||||
Both require an interactive terminal to the Hermes host. The rest of this skill
|
||||
is for when there is NO interactive TTY — Hermes running purely as a messaging
|
||||
gateway/bot where `/reload-mcp` triggers the flow with nobody at a prompt.
|
||||
|
||||
## Preferred Front Door: the Hermes Dashboard (try this BEFORE manual token surgery)
|
||||
|
||||
A remote Hermes gateway often also runs the **dashboard** web UI as a SEPARATE
|
||||
process (e.g. `hermes dashboard --host 0.0.0.0 --port <port>`; check with
|
||||
`ps aux | grep 'hermes dashboard'`). It exposes a connector/MCP console —
|
||||
endpoints like `/api/mcp/servers`, `/api/mcp/status`, and `/connectors` (all
|
||||
login-gated; a cookieless curl returning 401/302 confirms they exist).
|
||||
|
||||
**Why the dashboard solves the core problem:** when the user drives OAuth from
|
||||
the dashboard *in their own browser*, the redirect lands in a context the
|
||||
dashboard can capture — sidestepping the `127.0.0.1`-callback failure that breaks
|
||||
the CLI/manual flow. So the correct escalation order for "add or re-auth an OAuth
|
||||
MCP server on a remote gateway" is:
|
||||
|
||||
1. **Dashboard, in the user's browser** — the intended front door. Add servers, run OAuth, reload, all authenticated as the user. No copy-paste-callback dance, no hand-writing token files.
|
||||
2. **Manual token surgery (the rest of this skill)** — the FALLBACK for when there's no browser session to the dashboard (pure-chat/headless context).
|
||||
|
||||
**Finding the dashboard's PUBLIC URL.** The dashboard binds internally to
|
||||
`0.0.0.0:<port>`, but the user needs the externally-reachable URL. Most deploy
|
||||
platforms inject it into the environment — grep for it rather than making the
|
||||
user hunt:
|
||||
|
||||
```bash
|
||||
env | grep -iE "HERMES_DASHBOARD_PUBLIC_URL|RAILWAY_PUBLIC_DOMAIN|RAILWAY_STATIC_URL|RAILWAY_SERVICE_.*_URL|PUBLIC_URL|BASE_URL|DOMAIN" \
|
||||
| sed -E 's/(TOKEN|SECRET|KEY|PASSWORD)=.*/\1=***REDACTED***/I'
|
||||
```
|
||||
|
||||
`HERMES_DASHBOARD_PUBLIC_URL` is authoritative when present. On Railway also check
|
||||
`RAILWAY_PUBLIC_DOMAIN` / `RAILWAY_STATIC_URL` (the `*.up.railway.app` host) and
|
||||
`RAILWAY_SERVICE_*_URL` vars, which sometimes carry a friendlier custom domain.
|
||||
Hand the user the full `https://` URL and point them at the Connectors/MCP
|
||||
section. ALWAYS pipe through the `sed` redaction above — these env greps sit next
|
||||
to `*_TOKEN`/`*_SECRET` vars.
|
||||
|
||||
**What the dashboard does NOT fix (still host-side / shell):** stdio servers that
|
||||
need shell auth state (a CLI `login` command whose credentials may not persist
|
||||
across restarts) and anything reading credentials from `$HERMES_HOME/.env`. Those
|
||||
are out of the dashboard's scope regardless.
|
||||
|
||||
## The Workaround
|
||||
|
||||
Do the OAuth dance manually, then write the resulting tokens into the exact files
|
||||
Hermes' `HermesTokenStorage` would have written, so on `/reload-mcp` Hermes finds
|
||||
cached tokens and skips the browser flow entirely.
|
||||
|
||||
Run the shell commands below through the `terminal` tool on the gateway host and
|
||||
do the Python steps (PKCE generation, token exchange, file writes) via
|
||||
`execute_code` or a `terminal` python3 invocation — file writes must happen in
|
||||
the SAME code block as the token exchange (see pitfall 16).
|
||||
|
||||
### 1. Confirm it's a remote gateway
|
||||
|
||||
```bash
|
||||
env | grep -iE "HERMES|RAILWAY|CONTAINER"
|
||||
echo "$DISPLAY $WAYLAND_DISPLAY $SSH_CLIENT"
|
||||
```
|
||||
|
||||
No display + a remote indicator = remote gateway. `tools/mcp_oauth.py::_can_open_browser()`
|
||||
uses these same env vars, so if Hermes' own auto-detect says "headless", the
|
||||
built-in flow won't work.
|
||||
|
||||
### 2. Find HERMES_HOME and the config path
|
||||
|
||||
```bash
|
||||
HERMES_HOME=$(python3 -c 'from hermes_constants import get_hermes_home; print(get_hermes_home())')
|
||||
echo "config: $HERMES_HOME/config.yaml"
|
||||
echo "tokens: $HERMES_HOME/mcp-tokens/"
|
||||
```
|
||||
|
||||
### 3. Discover OAuth metadata from the MCP server
|
||||
|
||||
MCP servers advertise their OAuth setup via RFC 9728 (OAuth 2.0 Protected
|
||||
Resource Metadata). The `WWW-Authenticate` header on a 401 tells you where to look:
|
||||
|
||||
```bash
|
||||
curl -sI https://mcp.example.com | grep -i www-authenticate
|
||||
# → Bearer realm="mcp", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"
|
||||
```
|
||||
|
||||
**Not every server returns `WWW-Authenticate`.** Some return a bare
|
||||
`{"errors":["Unauthorized"]}` 401 with no auth-discovery hint. When that happens,
|
||||
probe well-known paths directly:
|
||||
|
||||
```bash
|
||||
for p in \
|
||||
/.well-known/oauth-protected-resource \
|
||||
/.well-known/oauth-authorization-server \
|
||||
/.well-known/openid-configuration ; do
|
||||
echo "=== $p ==="
|
||||
curl -s -A "python-httpx/0.27" "https://mcp.example.com$p" | head -c 400; echo
|
||||
done
|
||||
```
|
||||
|
||||
Fetch the resource metadata to get `authorization_servers`, then fetch the AS's
|
||||
`/.well-known/oauth-authorization-server` to get `authorization_endpoint`,
|
||||
`token_endpoint`, and `registration_endpoint`.
|
||||
|
||||
Pitfall: many servers sit behind Cloudflare and 403 bare `urllib` user agents.
|
||||
Always set `User-Agent: python-httpx/0.27` (or similar) on requests in this flow.
|
||||
|
||||
### 4. Dynamic Client Registration (RFC 7591)
|
||||
|
||||
POST to the `registration_endpoint` with:
|
||||
|
||||
```json
|
||||
{
|
||||
"client_name": "Hermes Agent (manual OAuth)",
|
||||
"redirect_uris": ["http://127.0.0.1:8765/callback"],
|
||||
"grant_types": ["authorization_code", "refresh_token"],
|
||||
"response_types": ["code"],
|
||||
"token_endpoint_auth_method": "none",
|
||||
"scope": "<scopes_from_resource_metadata>"
|
||||
}
|
||||
```
|
||||
|
||||
Omit `scope` entirely if the AS's `scopes_supported` is empty — see step 5
|
||||
pitfall. Use port `8765` (or any port — nothing will listen).
|
||||
`token_endpoint_auth_method: none` marks this as a public PKCE client. Save the
|
||||
returned `client_id`.
|
||||
|
||||
### 5. Build the authorize URL with PKCE
|
||||
|
||||
Generate:
|
||||
- `code_verifier`: `secrets.token_urlsafe(64)[:128]`
|
||||
- `code_challenge`: `base64url(sha256(code_verifier))` (no padding)
|
||||
- `state`: `secrets.token_urlsafe(24)`
|
||||
|
||||
Query params: `response_type=code`, `client_id`, `redirect_uri`, `code_challenge`,
|
||||
`code_challenge_method=S256`, `state`, plus `resource=<mcp_server_url>` (RFC 8707 —
|
||||
many servers require this to bind the token to the specific MCP resource). Include
|
||||
`scope=<space-separated>` ONLY if the AS metadata's `scopes_supported` is a
|
||||
non-empty array AND/OR the resource metadata declares specific scopes. If
|
||||
`scopes_supported: []`, omit the `scope` parameter — the server grants its full
|
||||
default set on its own. Fabricating scope strings against an empty
|
||||
`scopes_supported` can cause `invalid_scope` errors on some ASes.
|
||||
|
||||
**Stash `code_verifier` and `state` to disk** (e.g. `/tmp/.mcp-oauth-work/<server>.json`,
|
||||
0600 perms). You need them for step 7, possibly across multiple chat turns.
|
||||
|
||||
### 6. Give the user the authorize URL
|
||||
|
||||
```
|
||||
Open this URL in your browser:
|
||||
<authorize_url>
|
||||
|
||||
After approving, your browser will try to load http://127.0.0.1:8765/callback
|
||||
and fail to connect — THAT'S EXPECTED. Just copy the entire URL from the
|
||||
address bar (it will contain ?code=...&state=...) and paste it back here.
|
||||
```
|
||||
|
||||
### 7. Exchange the code for tokens
|
||||
|
||||
When the user pastes the callback URL:
|
||||
|
||||
1. Parse `code` and `state` from the query string.
|
||||
2. **Verify `state` matches the stashed value** (CSRF check — do not skip).
|
||||
3. POST `application/x-www-form-urlencoded` to the `token_endpoint`:
|
||||
- `grant_type=authorization_code`
|
||||
- `code=<from callback>`
|
||||
- `redirect_uri=<same as step 4>`
|
||||
- `client_id=<from step 4>`
|
||||
- `code_verifier=<stashed>`
|
||||
- `resource=<mcp_server_url>` (if the AS required it in step 5, include here too)
|
||||
4. Response contains `access_token`, `refresh_token`, `token_type`, `expires_in`, `scope`.
|
||||
|
||||
### 8. Write tokens in Hermes' exact schema
|
||||
|
||||
`tools/mcp_oauth.py::HermesTokenStorage` expects two files under
|
||||
`$HERMES_HOME/mcp-tokens/` (create dir with `0o700`, files with `0o600`):
|
||||
|
||||
**`<server_name>.json`** — the `OAuthToken` pydantic model:
|
||||
```json
|
||||
{
|
||||
"access_token": "...",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 7200,
|
||||
"refresh_token": "...",
|
||||
"scope": "read write"
|
||||
}
|
||||
```
|
||||
|
||||
**`<server_name>.client.json`** — the `OAuthClientInformationFull` model:
|
||||
```json
|
||||
{
|
||||
"client_id": "...",
|
||||
"redirect_uris": ["http://127.0.0.1:8765/callback"],
|
||||
"grant_types": ["authorization_code", "refresh_token"],
|
||||
"response_types": ["code"],
|
||||
"token_endpoint_auth_method": "none",
|
||||
"scope": "read write",
|
||||
"client_name": "..."
|
||||
}
|
||||
```
|
||||
|
||||
Write each file via `json.dumps(..., indent=2)`. Sanitize the filename with
|
||||
`re.sub(r'[^\w\-]', '_', server_name)[:128]` — this matches `_safe_filename()` in
|
||||
Hermes' token storage.
|
||||
|
||||
### 9. Add the server to config.yaml
|
||||
|
||||
```yaml
|
||||
mcp_servers:
|
||||
<name>:
|
||||
url: "https://mcp.example.com"
|
||||
auth: oauth
|
||||
timeout: 180
|
||||
connect_timeout: 60
|
||||
```
|
||||
|
||||
### 10. Smoke-test the token BEFORE asking the user to reload
|
||||
|
||||
Manually POST an MCP `initialize` request to confirm the token works end-to-end —
|
||||
this catches scope misconfigurations, wrong `resource` values, and CF blocks
|
||||
before the user is confused by another "No MCP tools available" reload:
|
||||
|
||||
```python
|
||||
body = json.dumps({
|
||||
"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
||||
"params": {
|
||||
"protocolVersion": "2025-06-18",
|
||||
"capabilities": {},
|
||||
"clientInfo": {"name": "hermes-debug", "version": "1.0"},
|
||||
},
|
||||
}).encode()
|
||||
# POST to the MCP URL with:
|
||||
# Authorization: Bearer <access_token>
|
||||
# Accept: application/json, text/event-stream
|
||||
# Content-Type: application/json
|
||||
# MCP-Protocol-Version: 2025-06-18
|
||||
# User-Agent: python-httpx/0.27
|
||||
```
|
||||
|
||||
Expect HTTP 200 with `Content-Type: text/event-stream` and a JSON-RPC result
|
||||
containing `serverInfo` and `capabilities`. **Do not use `urllib` with its default
|
||||
UA** — Cloudflare will 403 you even though Hermes (which uses httpx) will succeed.
|
||||
`scripts/diagnose-oauth-mcp.py` automates this smoke test.
|
||||
|
||||
### 11. Tell the user to run `/reload-mcp`
|
||||
|
||||
On reload, Hermes sees `auth: oauth`, calls `HermesTokenStorage.get_tokens()`,
|
||||
finds your cached tokens, skips the browser flow, and registers `mcp_<name>_*`
|
||||
tools. Refresh happens automatically before `expires_in` elapses.
|
||||
|
||||
## Pitfalls & Lessons Learned
|
||||
|
||||
1. **Do not assume "headless" means "OAuth impossible."** The built-in flow works fine for local CLI; the issue is strictly remote deployments where the user's browser and the Hermes process are on different machines. Check the execution environment before claiming OAuth isn't an option.
|
||||
|
||||
2. **Read the source, not just the skill docs.** `tools/mcp_oauth.py` and the MCP config reference in `website/docs/` are the authoritative references. Grep the tree before telling the user a feature "doesn't exist."
|
||||
|
||||
3. **Cloudflare UA filter.** Many MCP/OAuth providers front their infra with Cloudflare, which 403s `python-urllib/*` user agents on metadata endpoints even though those endpoints are public. Set `User-Agent: python-httpx/0.27` (or any browser-like string) on every request in this flow. Hermes itself uses httpx, so this is never a problem in the real connection path.
|
||||
|
||||
4. **Include `resource` in both authorize and token requests.** RFC 8707 resource indicators are not optional for most modern MCP servers — they bind the issued token to the specific MCP resource URL. Leaving it out sometimes still works but may yield a token that later fails at the MCP server with a scope/audience error.
|
||||
|
||||
5. **Trailing slash matters.** Some servers advertise the resource as `https://mcp.example.com/` with a trailing slash and reject tokens issued against the no-slash variant. Copy the `resource` value verbatim from the `.well-known/oauth-protected-resource` response.
|
||||
|
||||
6. **`/reload-mcp` is silent on failure.** If the reload shows "No MCP tools available" with no `change_detail` line, a server is in config but failed to connect and no error bubbled up. Tail the error log, smoke-test the token directly with a manual `initialize` POST, and — if everything looks good — ask for a full process restart.
|
||||
|
||||
7. **Circuit breaker can survive `/reload-mcp`.** `tools/mcp_tool.py` keeps a module-level error-count dict with a small threshold. Once tripped (e.g. after token expiry produces several consecutive failures), the tool handler can short-circuit before calling the server, so no successful call resets the counter. Symptom: reload says "Reconnected: X" but subsequent calls still fail with "server unreachable" in the same conversation. Recovery order: try `/reload-mcp` FIRST (cheap, no chat-process blip) — on current builds it can clear the counter; only escalate to a full gateway process restart if a live call STILL short-circuits after reload. Do not lead with "you must restart."
|
||||
|
||||
8. **Refresh on an expired access_token + a tripped breaker is a deadlock.** The auto-refresh logic runs inside the MCP call path, which the breaker short-circuits once tripped. Manually refreshing the token on disk does not help by itself — pair a manual token refresh with a full restart, not a `/reload-mcp`.
|
||||
|
||||
9. **`invalid_grant` on a manual refresh means the refresh token is DEAD — re-auth is the only fix, do not loop.** When the access_token has been expired long enough, the refresh_token can also be revoked/expired server-side. A `grant_type=refresh_token` POST then returns HTTP 400 `{"error":"invalid_grant",...}` (wording varies: "Grant not found", "Token expired", "refresh token is invalid"). There is NO recovery from the gateway side. Hand back to the user with two options: (a) re-run the full manual OAuth dance (steps 3–10), or (b) if the provider offers a static personal API key, switch to that — no refresh/expiry cycle, more durable for an unattended remote gateway. Detect early: before any create/update operation against an OAuth MCP, check `expires_at` vs `time.time()`; if already expired, attempt the refresh first and surface `invalid_grant` immediately rather than failing mid-task.
|
||||
|
||||
10. **A successful refresh that STILL yields a rejected token = server-side SESSION revocation; only a fresh authorization_code flow fixes it.** Distinct from pitfall 9. The stored token file can look healthy (`expires_at` well out, refresh_token present), yet a live `initialize` POST returns `401 invalid_token` with a JSON-RPC body like `{"error":{"code":-32002,"message":"Session expired. Please re-authenticate."}}`. The `grant_type=refresh_token` POST may **succeed** (HTTP 200, new access_token) — yet the brand-new token gets the SAME `-32002`. The provider revoked the underlying MCP *session* server-side; the OAuth refresh chain re-mints credentials but cannot re-establish a revoked session. Decision rule when an OAuth MCP reports "not connected": (1) smoke-test the stored access_token with a manual `initialize` POST; (2) if `401 invalid_token`, attempt a refresh and smoke-test the NEW token; (3a) new token works → write it + restart to clear the breaker; (3b) new token STILL gets `-32002`/"Session expired" → stop, this is session revocation, hand the user the authorize URL for a full re-auth. `scripts/diagnose-oauth-mcp.py` automates steps 1–2 and prints which branch you're in. For an unattended gateway whose session keeps getting revoked, prefer a static Personal API key. See `references/stripe-mcp-oauth-revocation.md` for a worked example of a provider that revokes weekly.
|
||||
|
||||
11. **Client info file is NOT optional.** Hermes needs `<server>.client.json` to know the `client_id` for refresh grants. Skipping it means the first refresh fails and the user has to re-auth — writing both files is the whole point of this skill.
|
||||
|
||||
12. **Never hand-type the redirect URL for the user to open.** Generate the authorize URL programmatically with `urllib.parse.urlencode()`. Spaces in scopes and special chars in `state` break string-concatenated URLs.
|
||||
|
||||
13. **Security: the stash file contains the `code_verifier`.** Delete `/tmp/.mcp-oauth-work/<server>.json` immediately after successful token exchange. There's no reason to keep a proof-of-identity secret around once it's consumed.
|
||||
|
||||
14. **Write what the token endpoint actually returned.** The AS may grant a narrower (or wider) scope than requested. Write the `scope` from the token-exchange response to `<server>.json`, not what you asked for in step 5. When `scopes_supported: []`, the explicit scope list you send IS authoritative both ways: some servers grant exactly what you list (pass narrow scopes for least-privilege, or enumerate the full set if the user needs everything), and some won't echo the granted scope back at registration time — only the token-exchange response is authoritative.
|
||||
|
||||
15. **OAuth tokens often double as Bearer tokens against the provider's public REST API.** The access_token in `<server>.json` is frequently not "MCP-only" — `Authorization: Bearer <token>` against the provider's documented REST API succeeds whenever the corresponding resource scope was granted. This is the OAuth 2.0 spec, not a provider quirk. When the MCP server is read-only but you need a write operation, check whether the OAuth token can hit the provider's REST API directly before suggesting a separate API key.
|
||||
|
||||
16. **Secret redaction can mask tokens in tool output.** If secret redaction is enabled, tokens and long opaque strings render as `***` in tool-result output, so you cannot `print(response)` to keep the access_token visible across turns. Combined with single-use `code` values from authorization_code grants: if you print the token-exchange response, you may lose the token AND consume the code, forcing a restart with a fresh authorize URL. **Always write the access_token directly to its final destination file in the SAME code block that performs the token exchange.** If you must print for debugging, print only `len(access_token)`, `token_type`, `scope`, `expires_in` — never the secret.
|
||||
|
||||
17. **GitHub MCP (`api.githubcopilot.com/mcp/`) uses a pre-registered confidential OAuth App, not DCR + PKCE-public.** Its client info ships with a real `client_secret` and `token_endpoint_auth_method: client_secret_post`. The token-exchange POST to `https://github.com/login/oauth/access_token` must include `client_secret` as a form field alongside `client_id`, `code`, `code_verifier`, and `redirect_uri` (PKCE is still honored on top of the secret). The redirect URI is **fixed** in the OAuth App config — you cannot change it, so the manual listener-port trick doesn't apply; the user just lets the browser fail to connect on that port and pastes the address-bar URL back.
|
||||
|
||||
## What NOT to do
|
||||
|
||||
- **Don't use `mcp-remote` as a fallback.** It runs an npx subprocess whose OAuth callback server ALSO sits on the remote container's localhost — same problem. `mcp-remote` only helps when the MCP client doesn't speak remote HTTP at all (Hermes does natively).
|
||||
- **Don't push "paste your API token and I'll add headers"** if the user explicitly asked for OAuth. Offer the static-token shortcut only after explaining why the native OAuth flow fails in remote deployments. Respect the user's choice to do the extra legwork for rotation-free, scope-limited access.
|
||||
- **Don't claim Hermes doesn't support a feature without reading the source.** Grep the source tree before making capability claims.
|
||||
|
||||
## Quick Reference Files
|
||||
|
||||
- `scripts/diagnose-oauth-mcp.py` — re-runnable, read-only-by-default diagnostic. Given a server name, it smoke-tests the stored access_token, attempts a refresh, smoke-tests the new token, and prints exactly which recovery branch you're in (`TOKEN_OK` = breaker/restart, `REFRESH_FIXED` = persist+restart, `SESSION_REVOKED` = full re-auth, `REFRESH_DEAD` = full re-auth/API key). Pass `--write` to persist a working refreshed token atomically. Never prints secret values. **Run this FIRST when an OAuth MCP server reports "not connected"** — it encodes the pitfall 7/9/10 decision tree.
|
||||
- `references/stripe-mcp-oauth-revocation.md` — a worked example (Stripe) of a provider that revokes its OAuth session on a recurring basis, and the durable fix: switch to a static restricted API key.
|
||||
|
||||
## Related
|
||||
|
||||
- `native-mcp` — general guide to configuring MCP in Hermes. Authoritative config reference lives there.
|
||||
- `mcporter` — the external CLI bridge, for ad-hoc MCP calls outside of Hermes' config.
|
||||
@@ -0,0 +1,138 @@
|
||||
---
|
||||
title: "Mcporter — List, auth, and call MCP servers/tools from the terminal"
|
||||
sidebar_label: "Mcporter"
|
||||
description: "List, auth, and call MCP servers/tools from the terminal"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Mcporter
|
||||
|
||||
List, auth, and call MCP servers/tools from the terminal.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mcp/mcporter` |
|
||||
| Path | `optional-skills/mcp\mcporter` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | community |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `MCP`, `Tools`, `API`, `Integrations`, `Interop` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# mcporter
|
||||
|
||||
Use `mcporter` to discover, call, and manage [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) servers and tools directly from the terminal.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Requires Node.js:
|
||||
```bash
|
||||
# No install needed (runs via npx)
|
||||
npx mcporter list
|
||||
|
||||
# Or install globally
|
||||
npm install -g mcporter
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# List MCP servers already configured on this machine
|
||||
mcporter list
|
||||
|
||||
# List tools for a specific server with schema details
|
||||
mcporter list <server> --schema
|
||||
|
||||
# Call a tool
|
||||
mcporter call <server.tool> key=value
|
||||
```
|
||||
|
||||
## Discovering MCP Servers
|
||||
|
||||
mcporter auto-discovers servers configured by other MCP clients (Claude Desktop, Cursor, etc.) on the machine. To find new servers to use, browse registries like [mcpfinder.dev](https://mcpfinder.dev) or [mcp.so](https://mcp.so), then connect ad-hoc:
|
||||
|
||||
```bash
|
||||
# Connect to any MCP server by URL (no config needed)
|
||||
mcporter list --http-url https://some-mcp-server.com --name my_server
|
||||
|
||||
# Or run a stdio server on the fly
|
||||
mcporter list --stdio "npx -y @modelcontextprotocol/server-filesystem" --name fs
|
||||
```
|
||||
|
||||
## Calling Tools
|
||||
|
||||
```bash
|
||||
# Key=value syntax
|
||||
mcporter call linear.list_issues team=ENG limit:5
|
||||
|
||||
# Function syntax
|
||||
mcporter call "linear.create_issue(title: \"Bug fix needed\")"
|
||||
|
||||
# Ad-hoc HTTP server (no config needed)
|
||||
mcporter call https://api.example.com/mcp.fetch url=https://example.com
|
||||
|
||||
# Ad-hoc stdio server
|
||||
mcporter call --stdio "bun run ./server.ts" scrape url=https://example.com
|
||||
|
||||
# JSON payload
|
||||
mcporter call <server.tool> --args '{"limit": 5}'
|
||||
|
||||
# Machine-readable output (recommended for Hermes)
|
||||
mcporter call <server.tool> key=value --output json
|
||||
```
|
||||
|
||||
## Auth and Config
|
||||
|
||||
```bash
|
||||
# OAuth login for a server
|
||||
mcporter auth <server | url> [--reset]
|
||||
|
||||
# Manage config
|
||||
mcporter config list
|
||||
mcporter config get <key>
|
||||
mcporter config add <server>
|
||||
mcporter config remove <server>
|
||||
mcporter config import <path>
|
||||
```
|
||||
|
||||
Config file location: `./config/mcporter.json` (override with `--config`).
|
||||
|
||||
## Daemon
|
||||
|
||||
For persistent server connections:
|
||||
```bash
|
||||
mcporter daemon start
|
||||
mcporter daemon status
|
||||
mcporter daemon stop
|
||||
mcporter daemon restart
|
||||
```
|
||||
|
||||
## Code Generation
|
||||
|
||||
```bash
|
||||
# Generate a CLI wrapper for an MCP server
|
||||
mcporter generate-cli --server <name>
|
||||
mcporter generate-cli --command <url>
|
||||
|
||||
# Inspect a generated CLI
|
||||
mcporter inspect-cli <path> [--json]
|
||||
|
||||
# Generate TypeScript types/client
|
||||
mcporter emit-ts <server> --mode client
|
||||
mcporter emit-ts <server> --mode types
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Use `--output json` for structured output that's easier to parse
|
||||
- Ad-hoc servers (HTTP URL or `--stdio` command) work without any config — useful for one-off calls
|
||||
- OAuth auth may require interactive browser flow — use `terminal(command="mcporter auth <server>", pty=true)` if needed
|
||||
@@ -0,0 +1,316 @@
|
||||
---
|
||||
title: "Openclaw Migration — Import an OpenClaw setup (memories, skills) into Hermes"
|
||||
sidebar_label: "Openclaw Migration"
|
||||
description: "Import an OpenClaw setup (memories, skills) into Hermes"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Openclaw Migration
|
||||
|
||||
Import an OpenClaw setup (memories, skills) into Hermes.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/migration/openclaw-migration` |
|
||||
| Path | `optional-skills/migration\openclaw-migration` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Hermes Agent (Nous Research) |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Migration`, `OpenClaw`, `Hermes`, `Memory`, `Persona`, `Import` |
|
||||
| Related skills | [`hermes-agent`](/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-hermes-agent) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# OpenClaw -> Hermes Migration
|
||||
|
||||
Use this skill when a user wants to move their OpenClaw setup into Hermes Agent with minimal manual cleanup.
|
||||
|
||||
## CLI Command
|
||||
|
||||
For a quick, non-interactive migration, use the built-in CLI command:
|
||||
|
||||
```bash
|
||||
hermes claw migrate # Full interactive migration
|
||||
hermes claw migrate --dry-run # Preview what would be migrated
|
||||
hermes claw migrate --preset user-data # Migrate without secrets
|
||||
hermes claw migrate --overwrite # Overwrite existing conflicts
|
||||
hermes claw migrate --source /custom/path/.openclaw # Custom source
|
||||
```
|
||||
|
||||
The CLI command runs the same migration script described below. Use this skill (via the agent) when you want an interactive, guided migration with dry-run previews and per-item conflict resolution.
|
||||
|
||||
**First-time setup:** The `hermes setup` wizard automatically detects `~/.openclaw` and offers migration before configuration begins.
|
||||
|
||||
## What this skill does
|
||||
|
||||
It uses `scripts/openclaw_to_hermes.py` to:
|
||||
|
||||
- import `SOUL.md` into the Hermes home directory as `SOUL.md`
|
||||
- transform OpenClaw `MEMORY.md` and `USER.md` into Hermes memory entries
|
||||
- merge OpenClaw command approval patterns into Hermes `command_allowlist`
|
||||
- migrate Hermes-compatible messaging settings such as `TELEGRAM_ALLOWED_USERS`, and map OpenClaw workspace settings to Hermes working-directory configuration
|
||||
- copy OpenClaw skills into `~/.hermes/skills/openclaw-imports/`
|
||||
- optionally copy the OpenClaw workspace instructions file into a chosen Hermes workspace
|
||||
- mirror compatible workspace assets such as `workspace/tts/` into `~/.hermes/tts/`
|
||||
- archive non-secret docs that do not have a direct Hermes destination
|
||||
- produce a structured report listing migrated items, conflicts, skipped items, and reasons
|
||||
|
||||
## Path resolution
|
||||
|
||||
The helper script lives in this skill directory at:
|
||||
|
||||
- `scripts/openclaw_to_hermes.py`
|
||||
|
||||
When this skill is installed from the Skills Hub, the normal location is:
|
||||
|
||||
- `~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py`
|
||||
|
||||
Do not guess a shorter path like `~/.hermes/skills/openclaw-migration/...`.
|
||||
|
||||
Before running the helper:
|
||||
|
||||
1. Prefer the installed path under `~/.hermes/skills/migration/openclaw-migration/`.
|
||||
2. If that path fails, inspect the installed skill directory and resolve the script relative to the installed `SKILL.md`.
|
||||
3. Only use `find` as a fallback if the installed location is missing or the skill was moved manually.
|
||||
4. When calling the terminal tool, do not pass `workdir: "~"`. Use an absolute directory such as the user's home directory, or omit `workdir` entirely.
|
||||
|
||||
With `--migrate-secrets`, it will also import a small allowlisted set of Hermes-compatible secrets, currently:
|
||||
|
||||
- `TELEGRAM_BOT_TOKEN`
|
||||
|
||||
## Default workflow
|
||||
|
||||
1. Inspect first with a dry run.
|
||||
2. Present a simple summary of what can be migrated, what cannot be migrated, and what would be archived.
|
||||
3. If the `clarify` tool is available, use it for user decisions instead of asking for a free-form prose reply.
|
||||
4. If the dry run finds imported skill directory conflicts, ask how those should be handled before executing.
|
||||
5. Ask the user to choose between the two supported migration modes before executing.
|
||||
6. Ask for a target workspace path only if the user wants the workspace instructions file brought over.
|
||||
7. Execute the migration with the matching preset and flags.
|
||||
8. Summarize the results, especially:
|
||||
- what was migrated
|
||||
- what was archived for manual review
|
||||
- what was skipped and why
|
||||
|
||||
## User interaction protocol
|
||||
|
||||
Hermes CLI supports the `clarify` tool for interactive prompts, but it is limited to:
|
||||
|
||||
- one choice at a time
|
||||
- up to 4 predefined choices
|
||||
- an automatic `Other` free-text option
|
||||
|
||||
It does **not** support true multi-select checkboxes in a single prompt.
|
||||
|
||||
For every `clarify` call:
|
||||
|
||||
- always include a non-empty `question`
|
||||
- include `choices` only for real selectable prompts
|
||||
- keep `choices` to 2-4 plain string options
|
||||
- never emit placeholder or truncated options such as `...`
|
||||
- never pad or stylize choices with extra whitespace
|
||||
- never include fake form fields in the question such as `enter directory here`, blank lines to fill in, or underscores like `_____`
|
||||
- for open-ended path questions, ask only the plain sentence; the user types in the normal CLI prompt below the panel
|
||||
|
||||
If a `clarify` call returns an error, inspect the error text, correct the payload, and retry once with a valid `question` and clean choices.
|
||||
|
||||
When `clarify` is available and the dry run reveals any required user decision, your **next action must be a `clarify` tool call**.
|
||||
Do not end the turn with a normal assistant message such as:
|
||||
|
||||
- "Let me present the choices"
|
||||
- "What would you like to do?"
|
||||
- "Here are the options"
|
||||
|
||||
If a user decision is required, collect it via `clarify` before producing more prose.
|
||||
If multiple unresolved decisions remain, do not insert an explanatory assistant message between them. After one `clarify` response is received, your next action should usually be the next required `clarify` call.
|
||||
|
||||
Treat `workspace-agents` as an unresolved decision whenever the dry run reports:
|
||||
|
||||
- `kind="workspace-agents"`
|
||||
- `status="skipped"`
|
||||
- reason containing `No workspace target was provided`
|
||||
|
||||
In that case, you must ask about workspace instructions before execution. Do not silently treat that as a decision to skip.
|
||||
|
||||
Because of that limitation, use this simplified decision flow:
|
||||
|
||||
1. For `SOUL.md` conflicts, use `clarify` with choices such as:
|
||||
- `keep existing`
|
||||
- `overwrite with backup`
|
||||
- `review first`
|
||||
2. If the dry run shows one or more `kind="skill"` items with `status="conflict"`, use `clarify` with choices such as:
|
||||
- `keep existing skills`
|
||||
- `overwrite conflicting skills with backup`
|
||||
- `import conflicting skills under renamed folders`
|
||||
3. For workspace instructions, use `clarify` with choices such as:
|
||||
- `skip workspace instructions`
|
||||
- `copy to a workspace path`
|
||||
- `decide later`
|
||||
4. If the user chooses to copy workspace instructions, ask a follow-up open-ended `clarify` question requesting an **absolute path**.
|
||||
5. If the user chooses `skip workspace instructions` or `decide later`, proceed without `--workspace-target`.
|
||||
5. For migration mode, use `clarify` with these 3 choices:
|
||||
- `user-data only`
|
||||
- `full compatible migration`
|
||||
- `cancel`
|
||||
6. `user-data only` means: migrate user data and compatible config, but do **not** import allowlisted secrets.
|
||||
7. `full compatible migration` means: migrate the same compatible user data plus the allowlisted secrets when present.
|
||||
8. If `clarify` is not available, ask the same question in normal text, but still constrain the answer to `user-data only`, `full compatible migration`, or `cancel`.
|
||||
|
||||
Execution gate:
|
||||
|
||||
- Do not execute while a `workspace-agents` skip caused by `No workspace target was provided` remains unresolved.
|
||||
- The only valid ways to resolve it are:
|
||||
- user explicitly chooses `skip workspace instructions`
|
||||
- user explicitly chooses `decide later`
|
||||
- user provides a workspace path after choosing `copy to a workspace path`
|
||||
- Absence of a workspace target in the dry run is not itself permission to execute.
|
||||
- Do not execute while any required `clarify` decision remains unresolved.
|
||||
|
||||
Use these exact `clarify` payload shapes as the default pattern:
|
||||
|
||||
- `{"question":"Your existing SOUL.md conflicts with the imported one. What should I do?","choices":["keep existing","overwrite with backup","review first"]}`
|
||||
- `{"question":"One or more imported OpenClaw skills already exist in Hermes. How should I handle those skill conflicts?","choices":["keep existing skills","overwrite conflicting skills with backup","import conflicting skills under renamed folders"]}`
|
||||
- `{"question":"Choose migration mode: migrate only user data, or run the full compatible migration including allowlisted secrets?","choices":["user-data only","full compatible migration","cancel"]}`
|
||||
- `{"question":"Do you want to copy the OpenClaw workspace instructions file into a Hermes workspace?","choices":["skip workspace instructions","copy to a workspace path","decide later"]}`
|
||||
- `{"question":"Please provide an absolute path where the workspace instructions should be copied."}`
|
||||
|
||||
## Decision-to-command mapping
|
||||
|
||||
Map user decisions to command flags exactly:
|
||||
|
||||
- If the user chooses `keep existing` for `SOUL.md`, do **not** add `--overwrite`.
|
||||
- If the user chooses `overwrite with backup`, add `--overwrite`.
|
||||
- If the user chooses `review first`, stop before execution and review the relevant files.
|
||||
- If the user chooses `keep existing skills`, add `--skill-conflict skip`.
|
||||
- If the user chooses `overwrite conflicting skills with backup`, add `--skill-conflict overwrite`.
|
||||
- If the user chooses `import conflicting skills under renamed folders`, add `--skill-conflict rename`.
|
||||
- If the user chooses `user-data only`, execute with `--preset user-data` and do **not** add `--migrate-secrets`.
|
||||
- If the user chooses `full compatible migration`, execute with `--preset full --migrate-secrets`.
|
||||
- Only add `--workspace-target` if the user explicitly provided an absolute workspace path.
|
||||
- If the user chooses `skip workspace instructions` or `decide later`, do not add `--workspace-target`.
|
||||
|
||||
Before executing, restate the exact command plan in plain language and make sure it matches the user's choices.
|
||||
|
||||
## Post-run reporting rules
|
||||
|
||||
After execution, treat the script's JSON output as the source of truth.
|
||||
|
||||
1. Base all counts on `report.summary`.
|
||||
2. Only list an item under "Successfully Migrated" if its `status` is exactly `migrated`.
|
||||
3. Do not claim a conflict was resolved unless the report shows that item as `migrated`.
|
||||
4. Do not say `SOUL.md` was overwritten unless the report item for `kind="soul"` has `status="migrated"`.
|
||||
5. If `report.summary.conflict > 0`, include a conflict section instead of silently implying success.
|
||||
6. If counts and listed items disagree, fix the list to match the report before responding.
|
||||
7. Include the `output_dir` path from the report when available so the user can inspect `report.json`, `summary.md`, backups, and archived files.
|
||||
8. For memory or user-profile overflow, do not say the entries were archived unless the report explicitly shows an archive path. If `details.overflow_file` exists, say the full overflow list was exported there.
|
||||
9. If a skill was imported under a renamed folder, report the final destination and mention `details.renamed_from`.
|
||||
10. If `report.skill_conflict_mode` is present, use it as the source of truth for the selected imported-skill conflict policy.
|
||||
11. If an item has `status="skipped"`, do not describe it as overwritten, backed up, migrated, or resolved.
|
||||
12. If `kind="soul"` has `status="skipped"` with reason `Target already matches source`, say it was left unchanged and do not mention a backup.
|
||||
13. If a renamed imported skill has an empty `details.backup`, do not imply the existing Hermes skill was renamed or backed up. Say only that the imported copy was placed in the new destination and reference `details.renamed_from` as the pre-existing folder that remained in place.
|
||||
|
||||
## Migration presets
|
||||
|
||||
Prefer these two presets in normal use:
|
||||
|
||||
- `user-data`
|
||||
- `full`
|
||||
|
||||
`user-data` includes:
|
||||
|
||||
- `soul`
|
||||
- `workspace-agents`
|
||||
- `memory`
|
||||
- `user-profile`
|
||||
- `messaging-settings`
|
||||
- `command-allowlist`
|
||||
- `skills`
|
||||
- `tts-assets`
|
||||
- `archive`
|
||||
|
||||
`full` includes everything in `user-data` plus:
|
||||
|
||||
- `secret-settings`
|
||||
|
||||
The helper script still supports category-level `--include` / `--exclude`, but treat that as an advanced fallback rather than the default UX.
|
||||
|
||||
## Commands
|
||||
|
||||
Dry run with full discovery:
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py
|
||||
```
|
||||
|
||||
When using the terminal tool, prefer an absolute invocation pattern such as:
|
||||
|
||||
```json
|
||||
{"command":"python /home/USER/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py","workdir":"/home/USER"}
|
||||
```
|
||||
|
||||
Dry run with the user-data preset:
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --preset user-data
|
||||
```
|
||||
|
||||
Execute a user-data migration:
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset user-data --skill-conflict skip
|
||||
```
|
||||
|
||||
Execute a full compatible migration:
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset full --migrate-secrets --skill-conflict skip
|
||||
```
|
||||
|
||||
Execute with workspace instructions included:
|
||||
|
||||
```bash
|
||||
python ~/.hermes/skills/migration/openclaw-migration/scripts/openclaw_to_hermes.py --execute --preset user-data --skill-conflict rename --workspace-target "/absolute/workspace/path"
|
||||
```
|
||||
|
||||
Do not use `$PWD` or the home directory as the workspace target by default. Ask for an explicit workspace path first.
|
||||
|
||||
## Important rules
|
||||
|
||||
1. Run a dry run before writing unless the user explicitly says to proceed immediately.
|
||||
2. Do not migrate secrets by default. Tokens, auth blobs, device credentials, and raw gateway config should stay out of Hermes unless the user explicitly asks for secret migration.
|
||||
3. Do not silently overwrite non-empty Hermes targets unless the user explicitly wants that. The helper script will preserve backups when overwriting is enabled.
|
||||
4. Always give the user the skipped-items report. That report is part of the migration, not an optional extra.
|
||||
5. Prefer the primary OpenClaw workspace (`~/.openclaw/workspace/`) over `workspace.default/`. Only use the default workspace as fallback when the primary files are missing.
|
||||
6. Even in secret-migration mode, only migrate secrets with a clean Hermes destination. Unsupported auth blobs must still be reported as skipped.
|
||||
7. If the dry run shows a large asset copy, a conflicting `SOUL.md`, or overflowed memory entries, call those out separately before execution.
|
||||
8. Default to `user-data only` if the user is unsure.
|
||||
9. Only include `workspace-agents` when the user has explicitly provided a destination workspace path.
|
||||
10. Treat category-level `--include` / `--exclude` as an advanced escape hatch, not the normal flow.
|
||||
11. Do not end the dry-run summary with a vague “What would you like to do?” if `clarify` is available. Use structured follow-up prompts instead.
|
||||
12. Do not use an open-ended `clarify` prompt when a real choice prompt would work. Prefer selectable choices first, then free text only for absolute paths or file review requests.
|
||||
13. After a dry run, never stop after summarizing if there is still an unresolved decision. Use `clarify` immediately for the highest-priority blocking decision.
|
||||
14. Priority order for follow-up questions:
|
||||
- `SOUL.md` conflict
|
||||
- imported skill conflicts
|
||||
- migration mode
|
||||
- workspace instructions destination
|
||||
15. Do not promise to present choices later in the same message. Present them by actually calling `clarify`.
|
||||
16. After the migration-mode answer, explicitly check whether `workspace-agents` is still unresolved. If it is, your next action must be the workspace-instructions `clarify` call.
|
||||
17. After any `clarify` answer, if another required decision remains, do not narrate what was just decided. Ask the next required question immediately.
|
||||
|
||||
## Expected result
|
||||
|
||||
After a successful run, the user should have:
|
||||
|
||||
- Hermes persona state imported
|
||||
- Hermes memory files populated with converted OpenClaw knowledge
|
||||
- OpenClaw skills available under `~/.hermes/skills/openclaw-imports/`
|
||||
- a migration report showing any conflicts, omissions, or unsupported data
|
||||
@@ -0,0 +1,366 @@
|
||||
---
|
||||
title: "Accelerate — Run PyTorch training across GPUs with minimal changes"
|
||||
sidebar_label: "Accelerate"
|
||||
description: "Run PyTorch training across GPUs with minimal changes"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Accelerate
|
||||
|
||||
Run PyTorch training across GPUs with minimal changes.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/accelerate` |
|
||||
| Path | `optional-skills/mlops\accelerate` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `accelerate`, `torch`, `transformers` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Distributed Training`, `HuggingFace`, `Accelerate`, `DeepSpeed`, `FSDP`, `Mixed Precision`, `PyTorch`, `DDP`, `Unified API`, `Simple` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# HuggingFace Accelerate - Unified Distributed Training
|
||||
|
||||
## Quick start
|
||||
|
||||
Accelerate simplifies distributed training to 4 lines of code.
|
||||
|
||||
**Installation**:
|
||||
```bash
|
||||
pip install accelerate
|
||||
```
|
||||
|
||||
**Convert PyTorch script** (4 lines):
|
||||
```python
|
||||
import torch
|
||||
+ from accelerate import Accelerator
|
||||
|
||||
+ accelerator = Accelerator()
|
||||
|
||||
model = torch.nn.Transformer()
|
||||
optimizer = torch.optim.Adam(model.parameters())
|
||||
dataloader = torch.utils.data.DataLoader(dataset)
|
||||
|
||||
+ model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
|
||||
|
||||
for batch in dataloader:
|
||||
optimizer.zero_grad()
|
||||
loss = model(batch)
|
||||
- loss.backward()
|
||||
+ accelerator.backward(loss)
|
||||
optimizer.step()
|
||||
```
|
||||
|
||||
**Run** (single command):
|
||||
```bash
|
||||
accelerate launch train.py
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: From single GPU to multi-GPU
|
||||
|
||||
**Original script**:
|
||||
```python
|
||||
# train.py
|
||||
import torch
|
||||
|
||||
model = torch.nn.Linear(10, 2).to('cuda')
|
||||
optimizer = torch.optim.Adam(model.parameters())
|
||||
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32)
|
||||
|
||||
for epoch in range(10):
|
||||
for batch in dataloader:
|
||||
batch = batch.to('cuda')
|
||||
optimizer.zero_grad()
|
||||
loss = model(batch).mean()
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
```
|
||||
|
||||
**With Accelerate** (4 lines added):
|
||||
```python
|
||||
# train.py
|
||||
import torch
|
||||
from accelerate import Accelerator # +1
|
||||
|
||||
accelerator = Accelerator() # +2
|
||||
|
||||
model = torch.nn.Linear(10, 2)
|
||||
optimizer = torch.optim.Adam(model.parameters())
|
||||
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32)
|
||||
|
||||
model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) # +3
|
||||
|
||||
for epoch in range(10):
|
||||
for batch in dataloader:
|
||||
# No .to('cuda') needed - automatic!
|
||||
optimizer.zero_grad()
|
||||
loss = model(batch).mean()
|
||||
accelerator.backward(loss) # +4
|
||||
optimizer.step()
|
||||
```
|
||||
|
||||
**Configure** (interactive):
|
||||
```bash
|
||||
accelerate config
|
||||
```
|
||||
|
||||
**Questions**:
|
||||
- Which machine? (single/multi GPU/TPU/CPU)
|
||||
- How many machines? (1)
|
||||
- Mixed precision? (no/fp16/bf16/fp8)
|
||||
- DeepSpeed? (no/yes)
|
||||
|
||||
**Launch** (works on any setup):
|
||||
```bash
|
||||
# Single GPU
|
||||
accelerate launch train.py
|
||||
|
||||
# Multi-GPU (8 GPUs)
|
||||
accelerate launch --multi_gpu --num_processes 8 train.py
|
||||
|
||||
# Multi-node
|
||||
accelerate launch --multi_gpu --num_processes 16 \
|
||||
--num_machines 2 --machine_rank 0 \
|
||||
--main_process_ip $MASTER_ADDR \
|
||||
train.py
|
||||
```
|
||||
|
||||
### Workflow 2: Mixed precision training
|
||||
|
||||
**Enable FP16/BF16**:
|
||||
```python
|
||||
from accelerate import Accelerator
|
||||
|
||||
# FP16 (with gradient scaling)
|
||||
accelerator = Accelerator(mixed_precision='fp16')
|
||||
|
||||
# BF16 (no scaling, more stable)
|
||||
accelerator = Accelerator(mixed_precision='bf16')
|
||||
|
||||
# FP8 (H100+)
|
||||
accelerator = Accelerator(mixed_precision='fp8')
|
||||
|
||||
model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
|
||||
|
||||
# Everything else is automatic!
|
||||
for batch in dataloader:
|
||||
with accelerator.autocast(): # Optional, done automatically
|
||||
loss = model(batch)
|
||||
accelerator.backward(loss)
|
||||
```
|
||||
|
||||
### Workflow 3: DeepSpeed ZeRO integration
|
||||
|
||||
**Enable DeepSpeed ZeRO-2** (pass a `DeepSpeedPlugin`, not a raw dict):
|
||||
```python
|
||||
from accelerate import Accelerator, DeepSpeedPlugin
|
||||
|
||||
deepspeed_plugin = DeepSpeedPlugin(
|
||||
zero_stage=2, # ZeRO-2
|
||||
offload_optimizer_device="none", # or "cpu" to offload
|
||||
gradient_accumulation_steps=4,
|
||||
)
|
||||
|
||||
accelerator = Accelerator(
|
||||
mixed_precision='bf16',
|
||||
deepspeed_plugin=deepspeed_plugin, # DeepSpeedPlugin instance (or dict[str, DeepSpeedPlugin])
|
||||
)
|
||||
|
||||
# Same code as before!
|
||||
model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
|
||||
```
|
||||
|
||||
**Or point at a full DeepSpeed JSON config via the plugin**:
|
||||
```python
|
||||
from accelerate import Accelerator, DeepSpeedPlugin
|
||||
|
||||
# hf_ds_config accepts a path to a DeepSpeed config JSON (or a dict)
|
||||
deepspeed_plugin = DeepSpeedPlugin(hf_ds_config="ds_config.json")
|
||||
accelerator = Accelerator(mixed_precision='bf16', deepspeed_plugin=deepspeed_plugin)
|
||||
```
|
||||
|
||||
**ds_config.json** (a raw DeepSpeed config — passed via the plugin, NOT via `--config_file`):
|
||||
```json
|
||||
{
|
||||
"fp16": {"enabled": false},
|
||||
"bf16": {"enabled": true},
|
||||
"zero_optimization": {
|
||||
"stage": 2,
|
||||
"offload_optimizer": {"device": "cpu"},
|
||||
"allgather_bucket_size": 5e8,
|
||||
"reduce_bucket_size": 5e8
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Or via interactive config**:
|
||||
```bash
|
||||
accelerate config
|
||||
# Select: DeepSpeed → ZeRO-2
|
||||
# This writes an accelerate YAML config (default: ~/.cache/huggingface/accelerate/default_config.yaml)
|
||||
```
|
||||
|
||||
**Launch** (`--config_file` expects an accelerate YAML, not a raw DeepSpeed JSON):
|
||||
```bash
|
||||
# Uses the default accelerate config written by `accelerate config`
|
||||
accelerate launch train.py
|
||||
|
||||
# Or point at a specific accelerate YAML
|
||||
accelerate launch --config_file accelerate_deepspeed.yaml train.py
|
||||
```
|
||||
|
||||
### Workflow 4: FSDP (Fully Sharded Data Parallel)
|
||||
|
||||
**Enable FSDP**:
|
||||
```python
|
||||
from accelerate import Accelerator, FullyShardedDataParallelPlugin
|
||||
|
||||
fsdp_plugin = FullyShardedDataParallelPlugin(
|
||||
sharding_strategy="FULL_SHARD", # ZeRO-3 equivalent
|
||||
auto_wrap_policy="transformer_based_wrap", # valid: transformer_based_wrap | size_based_wrap | no_wrap
|
||||
cpu_offload=False
|
||||
)
|
||||
|
||||
accelerator = Accelerator(
|
||||
mixed_precision='bf16',
|
||||
fsdp_plugin=fsdp_plugin
|
||||
)
|
||||
|
||||
model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
|
||||
```
|
||||
|
||||
**Or via config**:
|
||||
```bash
|
||||
accelerate config
|
||||
# Select: FSDP → Full Shard → No CPU Offload
|
||||
```
|
||||
|
||||
### Workflow 5: Gradient accumulation
|
||||
|
||||
**Accumulate gradients**:
|
||||
```python
|
||||
from accelerate import Accelerator
|
||||
|
||||
accelerator = Accelerator(gradient_accumulation_steps=4)
|
||||
|
||||
model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)
|
||||
|
||||
for batch in dataloader:
|
||||
with accelerator.accumulate(model): # Handles accumulation
|
||||
optimizer.zero_grad()
|
||||
loss = model(batch)
|
||||
accelerator.backward(loss)
|
||||
optimizer.step()
|
||||
```
|
||||
|
||||
**Effective batch size**: `batch_size * num_gpus * gradient_accumulation_steps`
|
||||
|
||||
## When to use vs alternatives
|
||||
|
||||
**Use Accelerate when**:
|
||||
- Want simplest distributed training
|
||||
- Need single script for any hardware
|
||||
- Use HuggingFace ecosystem
|
||||
- Want flexibility (DDP/DeepSpeed/FSDP/Megatron)
|
||||
- Need quick prototyping
|
||||
|
||||
**Key advantages**:
|
||||
- **4 lines**: Minimal code changes
|
||||
- **Unified API**: Same code for DDP, DeepSpeed, FSDP, Megatron
|
||||
- **Automatic**: Device placement, mixed precision, sharding
|
||||
- **Interactive config**: No manual launcher setup
|
||||
- **Single launch**: Works everywhere
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **PyTorch Lightning**: Need callbacks, high-level abstractions
|
||||
- **Ray Train**: Multi-node orchestration, hyperparameter tuning
|
||||
- **DeepSpeed**: Direct API control, advanced features
|
||||
- **Raw DDP**: Maximum control, minimal abstraction
|
||||
|
||||
## Common issues
|
||||
|
||||
**Issue: Wrong device placement**
|
||||
|
||||
Don't manually move to device:
|
||||
```python
|
||||
# WRONG
|
||||
batch = batch.to('cuda')
|
||||
|
||||
# CORRECT
|
||||
# Accelerate handles it automatically after prepare()
|
||||
```
|
||||
|
||||
**Issue: Gradient accumulation not working**
|
||||
|
||||
Use context manager:
|
||||
```python
|
||||
# CORRECT
|
||||
with accelerator.accumulate(model):
|
||||
optimizer.zero_grad()
|
||||
accelerator.backward(loss)
|
||||
optimizer.step()
|
||||
```
|
||||
|
||||
**Issue: Checkpointing in distributed**
|
||||
|
||||
Use accelerator methods:
|
||||
```python
|
||||
# Save only on main process
|
||||
if accelerator.is_main_process:
|
||||
accelerator.save_state('checkpoint/')
|
||||
|
||||
# Load on all processes
|
||||
accelerator.load_state('checkpoint/')
|
||||
```
|
||||
|
||||
**Issue: Different results with FSDP**
|
||||
|
||||
Ensure same random seed:
|
||||
```python
|
||||
from accelerate.utils import set_seed
|
||||
set_seed(42)
|
||||
```
|
||||
|
||||
## Advanced topics
|
||||
|
||||
**Megatron integration**: See [references/megatron-integration.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\accelerate/references/megatron-integration.md) for tensor parallelism, pipeline parallelism, and sequence parallelism setup.
|
||||
|
||||
**Custom plugins**: See [references/custom-plugins.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\accelerate/references/custom-plugins.md) for creating custom distributed plugins and advanced configuration.
|
||||
|
||||
**Performance tuning**: See [references/performance.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\accelerate/references/performance.md) for profiling, memory optimization, and best practices.
|
||||
|
||||
## Hardware requirements
|
||||
|
||||
- **CPU**: Works (slow)
|
||||
- **Single GPU**: Works
|
||||
- **Multi-GPU**: DDP (default), DeepSpeed, or FSDP
|
||||
- **Multi-node**: DDP, DeepSpeed, FSDP, Megatron
|
||||
- **TPU**: Supported
|
||||
- **Apple MPS**: Supported
|
||||
|
||||
**Launcher requirements**:
|
||||
- **DDP**: `torch.distributed.run` (built-in)
|
||||
- **DeepSpeed**: `deepspeed` (pip install deepspeed)
|
||||
- **FSDP**: PyTorch 1.12+ (built-in)
|
||||
- **Megatron**: Custom setup
|
||||
|
||||
## Resources
|
||||
|
||||
- Docs: https://huggingface.co/docs/accelerate
|
||||
- GitHub: https://github.com/huggingface/accelerate
|
||||
- Version: 1.11.0+
|
||||
- Tutorial: "Accelerate your scripts"
|
||||
- Examples: https://github.com/huggingface/accelerate/tree/main/examples
|
||||
- Used by: HuggingFace Transformers, TRL, PEFT, all HF libraries
|
||||
@@ -0,0 +1,425 @@
|
||||
---
|
||||
title: "Chroma — Embedding database for RAG and semantic search"
|
||||
sidebar_label: "Chroma"
|
||||
description: "Embedding database for RAG and semantic search"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Chroma
|
||||
|
||||
Embedding database for RAG and semantic search.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/chroma` |
|
||||
| Path | `optional-skills/mlops\chroma` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `chromadb`, `sentence-transformers` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `RAG`, `Chroma`, `Vector Database`, `Embeddings`, `Semantic Search`, `Open Source`, `Self-Hosted`, `Document Retrieval`, `Metadata Filtering` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Chroma - Open-Source Embedding Database
|
||||
|
||||
The AI-native database for building LLM applications with memory.
|
||||
|
||||
## When to use Chroma
|
||||
|
||||
**Use Chroma when:**
|
||||
- Building RAG (retrieval-augmented generation) applications
|
||||
- Need local/self-hosted vector database
|
||||
- Want open-source solution (Apache 2.0)
|
||||
- Prototyping in notebooks
|
||||
- Semantic search over documents
|
||||
- Storing embeddings with metadata
|
||||
|
||||
**Metrics**:
|
||||
- **24,300+ GitHub stars**
|
||||
- **1,900+ forks**
|
||||
- **v1.3.3** (stable, weekly releases)
|
||||
- **Apache 2.0 license**
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **Pinecone**: Managed cloud, auto-scaling
|
||||
- **FAISS**: Pure similarity search, no metadata
|
||||
- **Weaviate**: Production ML-native database
|
||||
- **Qdrant**: High performance, Rust-based
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Python
|
||||
pip install chromadb
|
||||
|
||||
# JavaScript/TypeScript
|
||||
npm install chromadb @chroma-core/default-embed
|
||||
```
|
||||
|
||||
### Basic usage (Python)
|
||||
|
||||
```python
|
||||
import chromadb
|
||||
|
||||
# Create client
|
||||
client = chromadb.Client()
|
||||
|
||||
# Create collection
|
||||
collection = client.create_collection(name="my_collection")
|
||||
|
||||
# Add documents
|
||||
collection.add(
|
||||
documents=["This is document 1", "This is document 2"],
|
||||
metadatas=[{"source": "doc1"}, {"source": "doc2"}],
|
||||
ids=["id1", "id2"]
|
||||
)
|
||||
|
||||
# Query
|
||||
results = collection.query(
|
||||
query_texts=["document about topic"],
|
||||
n_results=2
|
||||
)
|
||||
|
||||
print(results)
|
||||
```
|
||||
|
||||
## Core operations
|
||||
|
||||
### 1. Create collection
|
||||
|
||||
```python
|
||||
# Simple collection
|
||||
collection = client.create_collection("my_docs")
|
||||
|
||||
# With custom embedding function
|
||||
from chromadb.utils import embedding_functions
|
||||
|
||||
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
|
||||
api_key="your-key",
|
||||
model_name="text-embedding-3-small"
|
||||
)
|
||||
|
||||
collection = client.create_collection(
|
||||
name="my_docs",
|
||||
embedding_function=openai_ef
|
||||
)
|
||||
|
||||
# Get existing collection
|
||||
collection = client.get_collection("my_docs")
|
||||
|
||||
# Delete collection
|
||||
client.delete_collection("my_docs")
|
||||
```
|
||||
|
||||
### 2. Add documents
|
||||
|
||||
```python
|
||||
# Add with auto-generated IDs
|
||||
collection.add(
|
||||
documents=["Doc 1", "Doc 2", "Doc 3"],
|
||||
metadatas=[
|
||||
{"source": "web", "category": "tutorial"},
|
||||
{"source": "pdf", "page": 5},
|
||||
{"source": "api", "timestamp": "2025-01-01"}
|
||||
],
|
||||
ids=["id1", "id2", "id3"]
|
||||
)
|
||||
|
||||
# Add with custom embeddings
|
||||
collection.add(
|
||||
embeddings=[[0.1, 0.2, ...], [0.3, 0.4, ...]],
|
||||
documents=["Doc 1", "Doc 2"],
|
||||
ids=["id1", "id2"]
|
||||
)
|
||||
```
|
||||
|
||||
### 3. Query (similarity search)
|
||||
|
||||
```python
|
||||
# Basic query
|
||||
results = collection.query(
|
||||
query_texts=["machine learning tutorial"],
|
||||
n_results=5
|
||||
)
|
||||
|
||||
# Query with filters
|
||||
results = collection.query(
|
||||
query_texts=["Python programming"],
|
||||
n_results=3,
|
||||
where={"source": "web"}
|
||||
)
|
||||
|
||||
# Query with metadata filters
|
||||
results = collection.query(
|
||||
query_texts=["advanced topics"],
|
||||
where={
|
||||
"$and": [
|
||||
{"category": "tutorial"},
|
||||
{"difficulty": {"$gte": 3}}
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
# Access results
|
||||
print(results["documents"]) # List of matching documents
|
||||
print(results["metadatas"]) # Metadata for each doc
|
||||
print(results["distances"]) # Similarity scores
|
||||
print(results["ids"]) # Document IDs
|
||||
```
|
||||
|
||||
### 4. Get documents
|
||||
|
||||
```python
|
||||
# Get by IDs
|
||||
docs = collection.get(
|
||||
ids=["id1", "id2"]
|
||||
)
|
||||
|
||||
# Get with filters
|
||||
docs = collection.get(
|
||||
where={"category": "tutorial"},
|
||||
limit=10
|
||||
)
|
||||
|
||||
# Get all documents
|
||||
docs = collection.get()
|
||||
```
|
||||
|
||||
### 5. Update documents
|
||||
|
||||
```python
|
||||
# Update document content
|
||||
collection.update(
|
||||
ids=["id1"],
|
||||
documents=["Updated content"],
|
||||
metadatas=[{"source": "updated"}]
|
||||
)
|
||||
```
|
||||
|
||||
### 6. Delete documents
|
||||
|
||||
```python
|
||||
# Delete by IDs
|
||||
collection.delete(ids=["id1", "id2"])
|
||||
|
||||
# Delete with filter
|
||||
collection.delete(
|
||||
where={"source": "outdated"}
|
||||
)
|
||||
```
|
||||
|
||||
## Persistent storage
|
||||
|
||||
```python
|
||||
# Persist to disk
|
||||
client = chromadb.PersistentClient(path="./chroma_db")
|
||||
|
||||
collection = client.create_collection("my_docs")
|
||||
collection.add(documents=["Doc 1"], ids=["id1"])
|
||||
|
||||
# Data persisted automatically
|
||||
# Reload later with same path
|
||||
client = chromadb.PersistentClient(path="./chroma_db")
|
||||
collection = client.get_collection("my_docs")
|
||||
```
|
||||
|
||||
## Embedding functions
|
||||
|
||||
### Default (Sentence Transformers)
|
||||
|
||||
```python
|
||||
# Uses sentence-transformers by default
|
||||
collection = client.create_collection("my_docs")
|
||||
# Default model: all-MiniLM-L6-v2
|
||||
```
|
||||
|
||||
### OpenAI
|
||||
|
||||
```python
|
||||
from chromadb.utils import embedding_functions
|
||||
|
||||
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
|
||||
api_key="your-key",
|
||||
model_name="text-embedding-3-small"
|
||||
)
|
||||
|
||||
collection = client.create_collection(
|
||||
name="openai_docs",
|
||||
embedding_function=openai_ef
|
||||
)
|
||||
```
|
||||
|
||||
### HuggingFace
|
||||
|
||||
```python
|
||||
huggingface_ef = embedding_functions.HuggingFaceEmbeddingFunction(
|
||||
api_key="your-key",
|
||||
model_name="sentence-transformers/all-mpnet-base-v2"
|
||||
)
|
||||
|
||||
collection = client.create_collection(
|
||||
name="hf_docs",
|
||||
embedding_function=huggingface_ef
|
||||
)
|
||||
```
|
||||
|
||||
### Custom embedding function
|
||||
|
||||
```python
|
||||
from chromadb import Documents, EmbeddingFunction, Embeddings
|
||||
|
||||
class MyEmbeddingFunction(EmbeddingFunction):
|
||||
def __call__(self, input: Documents) -> Embeddings:
|
||||
# Your embedding logic
|
||||
return embeddings
|
||||
|
||||
my_ef = MyEmbeddingFunction()
|
||||
collection = client.create_collection(
|
||||
name="custom_docs",
|
||||
embedding_function=my_ef
|
||||
)
|
||||
```
|
||||
|
||||
## Metadata filtering
|
||||
|
||||
```python
|
||||
# Exact match
|
||||
results = collection.query(
|
||||
query_texts=["query"],
|
||||
where={"category": "tutorial"}
|
||||
)
|
||||
|
||||
# Comparison operators
|
||||
results = collection.query(
|
||||
query_texts=["query"],
|
||||
where={"page": {"$gt": 10}} # $gt, $gte, $lt, $lte, $ne
|
||||
)
|
||||
|
||||
# Logical operators
|
||||
results = collection.query(
|
||||
query_texts=["query"],
|
||||
where={
|
||||
"$and": [
|
||||
{"category": "tutorial"},
|
||||
{"difficulty": {"$lte": 3}}
|
||||
]
|
||||
} # Also: $or
|
||||
)
|
||||
|
||||
# Contains
|
||||
results = collection.query(
|
||||
query_texts=["query"],
|
||||
where={"tags": {"$in": ["python", "ml"]}}
|
||||
)
|
||||
```
|
||||
|
||||
## LangChain integration
|
||||
|
||||
```python
|
||||
from langchain_chroma import Chroma
|
||||
from langchain_openai import OpenAIEmbeddings
|
||||
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
||||
|
||||
# Split documents
|
||||
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000)
|
||||
docs = text_splitter.split_documents(documents)
|
||||
|
||||
# Create Chroma vector store
|
||||
vectorstore = Chroma.from_documents(
|
||||
documents=docs,
|
||||
embedding=OpenAIEmbeddings(),
|
||||
persist_directory="./chroma_db"
|
||||
)
|
||||
|
||||
# Query
|
||||
results = vectorstore.similarity_search("machine learning", k=3)
|
||||
|
||||
# As retriever
|
||||
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
|
||||
```
|
||||
|
||||
## LlamaIndex integration
|
||||
|
||||
```python
|
||||
from llama_index.vector_stores.chroma import ChromaVectorStore
|
||||
from llama_index.core import VectorStoreIndex, StorageContext
|
||||
import chromadb
|
||||
|
||||
# Initialize Chroma
|
||||
db = chromadb.PersistentClient(path="./chroma_db")
|
||||
collection = db.get_or_create_collection("my_collection")
|
||||
|
||||
# Create vector store
|
||||
vector_store = ChromaVectorStore(chroma_collection=collection)
|
||||
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
||||
|
||||
# Create index
|
||||
index = VectorStoreIndex.from_documents(
|
||||
documents,
|
||||
storage_context=storage_context
|
||||
)
|
||||
|
||||
# Query
|
||||
query_engine = index.as_query_engine()
|
||||
response = query_engine.query("What is machine learning?")
|
||||
```
|
||||
|
||||
## Server mode
|
||||
|
||||
```python
|
||||
# Run Chroma server
|
||||
# Terminal: chroma run --path ./chroma_db --port 8000
|
||||
|
||||
# Connect to server
|
||||
import chromadb
|
||||
from chromadb.config import Settings
|
||||
|
||||
client = chromadb.HttpClient(
|
||||
host="localhost",
|
||||
port=8000,
|
||||
settings=Settings(anonymized_telemetry=False)
|
||||
)
|
||||
|
||||
# Use as normal
|
||||
collection = client.get_or_create_collection("my_docs")
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
1. **Use persistent client** - Don't lose data on restart
|
||||
2. **Add metadata** - Enables filtering and tracking
|
||||
3. **Batch operations** - Add multiple docs at once
|
||||
4. **Choose right embedding model** - Balance speed/quality
|
||||
5. **Use filters** - Narrow search space
|
||||
6. **Unique IDs** - Avoid collisions
|
||||
7. **Regular backups** - Copy chroma_db directory
|
||||
8. **Monitor collection size** - Scale up if needed
|
||||
9. **Test embedding functions** - Ensure quality
|
||||
10. **Use server mode for production** - Better for multi-user
|
||||
|
||||
## Performance
|
||||
|
||||
| Operation | Latency | Notes |
|
||||
|-----------|---------|-------|
|
||||
| Add 100 docs | ~1-3s | With embedding |
|
||||
| Query (top 10) | ~50-200ms | Depends on collection size |
|
||||
| Metadata filter | ~10-50ms | Fast with proper indexing |
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/chroma-core/chroma ⭐ 24,300+
|
||||
- **Docs**: https://docs.trychroma.com
|
||||
- **Discord**: https://discord.gg/MMeYNTmh3x
|
||||
- **Version**: 1.3.3+
|
||||
- **License**: Apache 2.0
|
||||
@@ -0,0 +1,272 @@
|
||||
---
|
||||
title: "Clip — Zero-shot image classification and image-text search"
|
||||
sidebar_label: "Clip"
|
||||
description: "Zero-shot image classification and image-text search"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Clip
|
||||
|
||||
Zero-shot image classification and image-text search.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/clip` |
|
||||
| Path | `optional-skills/mlops\clip` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `transformers`, `torch`, `pillow` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Multimodal`, `CLIP`, `Vision-Language`, `Zero-Shot`, `Image Classification`, `OpenAI`, `Image Search`, `Cross-Modal Retrieval`, `Content Moderation` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# CLIP - Contrastive Language-Image Pre-Training
|
||||
|
||||
OpenAI's model that understands images from natural language.
|
||||
|
||||
## When to use CLIP
|
||||
|
||||
**Use when:**
|
||||
- Zero-shot image classification (no training data needed)
|
||||
- Image-text similarity/matching
|
||||
- Semantic image search
|
||||
- Content moderation (detect NSFW, violence)
|
||||
- Visual question answering
|
||||
- Cross-modal retrieval (image→text, text→image)
|
||||
|
||||
**Metrics**:
|
||||
- **25,300+ GitHub stars**
|
||||
- Trained on 400M image-text pairs
|
||||
- Matches ResNet-50 on ImageNet (zero-shot)
|
||||
- MIT License
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **BLIP-2**: Better captioning
|
||||
- **LLaVA**: Vision-language chat
|
||||
- **Segment Anything**: Image segmentation
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
pip install git+https://github.com/openai/CLIP.git
|
||||
pip install torch torchvision ftfy regex tqdm
|
||||
```
|
||||
|
||||
### Zero-shot classification
|
||||
|
||||
```python
|
||||
import torch
|
||||
import clip
|
||||
from PIL import Image
|
||||
|
||||
# Load model
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
model, preprocess = clip.load("ViT-B/32", device=device)
|
||||
|
||||
# Load image
|
||||
image = preprocess(Image.open("photo.jpg")).unsqueeze(0).to(device)
|
||||
|
||||
# Define possible labels
|
||||
text = clip.tokenize(["a dog", "a cat", "a bird", "a car"]).to(device)
|
||||
|
||||
# Compute similarity
|
||||
with torch.no_grad():
|
||||
image_features = model.encode_image(image)
|
||||
text_features = model.encode_text(text)
|
||||
|
||||
# Cosine similarity
|
||||
logits_per_image, logits_per_text = model(image, text)
|
||||
probs = logits_per_image.softmax(dim=-1).cpu().numpy()
|
||||
|
||||
# Print results
|
||||
labels = ["a dog", "a cat", "a bird", "a car"]
|
||||
for label, prob in zip(labels, probs[0]):
|
||||
print(f"{label}: {prob:.2%}")
|
||||
```
|
||||
|
||||
## Available models
|
||||
|
||||
```python
|
||||
# Models (sorted by size)
|
||||
models = [
|
||||
"RN50", # ResNet-50
|
||||
"RN101", # ResNet-101
|
||||
"ViT-B/32", # Vision Transformer (recommended)
|
||||
"ViT-B/16", # Better quality, slower
|
||||
"ViT-L/14", # Best quality, slowest
|
||||
]
|
||||
|
||||
model, preprocess = clip.load("ViT-B/32")
|
||||
```
|
||||
|
||||
| Model | Parameters | Speed | Quality |
|
||||
|-------|------------|-------|---------|
|
||||
| RN50 | 102M | Fast | Good |
|
||||
| ViT-B/32 | 151M | Medium | Better |
|
||||
| ViT-L/14 | 428M | Slow | Best |
|
||||
|
||||
## Image-text similarity
|
||||
|
||||
```python
|
||||
# Compute embeddings
|
||||
image_features = model.encode_image(image)
|
||||
text_features = model.encode_text(text)
|
||||
|
||||
# Normalize
|
||||
image_features /= image_features.norm(dim=-1, keepdim=True)
|
||||
text_features /= text_features.norm(dim=-1, keepdim=True)
|
||||
|
||||
# Cosine similarity
|
||||
similarity = (image_features @ text_features.T).item()
|
||||
print(f"Similarity: {similarity:.4f}")
|
||||
```
|
||||
|
||||
## Semantic image search
|
||||
|
||||
```python
|
||||
# Index images
|
||||
image_paths = ["img1.jpg", "img2.jpg", "img3.jpg"]
|
||||
image_embeddings = []
|
||||
|
||||
for img_path in image_paths:
|
||||
image = preprocess(Image.open(img_path)).unsqueeze(0).to(device)
|
||||
with torch.no_grad():
|
||||
embedding = model.encode_image(image)
|
||||
embedding /= embedding.norm(dim=-1, keepdim=True)
|
||||
image_embeddings.append(embedding)
|
||||
|
||||
image_embeddings = torch.cat(image_embeddings)
|
||||
|
||||
# Search with text query
|
||||
query = "a sunset over the ocean"
|
||||
text_input = clip.tokenize([query]).to(device)
|
||||
with torch.no_grad():
|
||||
text_embedding = model.encode_text(text_input)
|
||||
text_embedding /= text_embedding.norm(dim=-1, keepdim=True)
|
||||
|
||||
# Find most similar images
|
||||
similarities = (text_embedding @ image_embeddings.T).squeeze(0)
|
||||
top_k = similarities.topk(3)
|
||||
|
||||
for idx, score in zip(top_k.indices, top_k.values):
|
||||
print(f"{image_paths[idx]}: {score:.3f}")
|
||||
```
|
||||
|
||||
## Content moderation
|
||||
|
||||
```python
|
||||
# Define categories
|
||||
categories = [
|
||||
"safe for work",
|
||||
"not safe for work",
|
||||
"violent content",
|
||||
"graphic content"
|
||||
]
|
||||
|
||||
text = clip.tokenize(categories).to(device)
|
||||
|
||||
# Check image
|
||||
with torch.no_grad():
|
||||
logits_per_image, _ = model(image, text)
|
||||
probs = logits_per_image.softmax(dim=-1)
|
||||
|
||||
# Get classification
|
||||
max_idx = probs.argmax().item()
|
||||
max_prob = probs[0, max_idx].item()
|
||||
|
||||
print(f"Category: {categories[max_idx]} ({max_prob:.2%})")
|
||||
```
|
||||
|
||||
## Batch processing
|
||||
|
||||
```python
|
||||
# Process multiple images
|
||||
images = [preprocess(Image.open(f"img{i}.jpg")) for i in range(10)]
|
||||
images = torch.stack(images).to(device)
|
||||
|
||||
with torch.no_grad():
|
||||
image_features = model.encode_image(images)
|
||||
image_features /= image_features.norm(dim=-1, keepdim=True)
|
||||
|
||||
# Batch text
|
||||
texts = ["a dog", "a cat", "a bird"]
|
||||
text_tokens = clip.tokenize(texts).to(device)
|
||||
|
||||
with torch.no_grad():
|
||||
text_features = model.encode_text(text_tokens)
|
||||
text_features /= text_features.norm(dim=-1, keepdim=True)
|
||||
|
||||
# Similarity matrix (10 images × 3 texts)
|
||||
similarities = image_features @ text_features.T
|
||||
print(similarities.shape) # (10, 3)
|
||||
```
|
||||
|
||||
## Integration with vector databases
|
||||
|
||||
```python
|
||||
# Store CLIP embeddings in Chroma/FAISS
|
||||
import chromadb
|
||||
|
||||
client = chromadb.Client()
|
||||
collection = client.create_collection("image_embeddings")
|
||||
|
||||
# Add image embeddings
|
||||
for img_path, embedding in zip(image_paths, image_embeddings):
|
||||
collection.add(
|
||||
embeddings=[embedding.cpu().numpy().tolist()],
|
||||
metadatas=[{"path": img_path}],
|
||||
ids=[img_path]
|
||||
)
|
||||
|
||||
# Query with text
|
||||
query = "a sunset"
|
||||
text_embedding = model.encode_text(clip.tokenize([query]))
|
||||
results = collection.query(
|
||||
query_embeddings=[text_embedding.cpu().numpy().tolist()],
|
||||
n_results=5
|
||||
)
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
1. **Use ViT-B/32 for most cases** - Good balance
|
||||
2. **Normalize embeddings** - Required for cosine similarity
|
||||
3. **Batch processing** - More efficient
|
||||
4. **Cache embeddings** - Expensive to recompute
|
||||
5. **Use descriptive labels** - Better zero-shot performance
|
||||
6. **GPU recommended** - 10-50× faster
|
||||
7. **Preprocess images** - Use provided preprocess function
|
||||
|
||||
## Performance
|
||||
|
||||
| Operation | CPU | GPU (V100) |
|
||||
|-----------|-----|------------|
|
||||
| Image encoding | ~200ms | ~20ms |
|
||||
| Text encoding | ~50ms | ~5ms |
|
||||
| Similarity compute | <1ms | <1ms |
|
||||
|
||||
## Limitations
|
||||
|
||||
1. **Not for fine-grained tasks** - Best for broad categories
|
||||
2. **Requires descriptive text** - Vague labels perform poorly
|
||||
3. **Biased on web data** - May have dataset biases
|
||||
4. **No bounding boxes** - Whole image only
|
||||
5. **Limited spatial understanding** - Position/counting weak
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/openai/CLIP ⭐ 25,300+
|
||||
- **Paper**: https://arxiv.org/abs/2103.00020
|
||||
- **Colab**: https://colab.research.google.com/github/openai/clip/
|
||||
- **License**: MIT
|
||||
+512
@@ -0,0 +1,512 @@
|
||||
---
|
||||
title: "Evaluating Llms Harness — lm-eval-harness: benchmark LLMs (MMLU, GSM8K, etc.)"
|
||||
sidebar_label: "Evaluating Llms Harness"
|
||||
description: "lm-eval-harness: benchmark LLMs (MMLU, GSM8K, etc.)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Evaluating Llms Harness
|
||||
|
||||
lm-eval-harness: benchmark LLMs (MMLU, GSM8K, etc.).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/evaluating-llms-harness` |
|
||||
| Path | `optional-skills/mlops\evaluation\evaluating-llms-harness` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `lm-eval`, `transformers`, `vllm` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Evaluation`, `LM Evaluation Harness`, `Benchmarking`, `MMLU`, `HumanEval`, `GSM8K`, `EleutherAI`, `Model Quality`, `Academic Benchmarks`, `Industry Standard` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# lm-evaluation-harness - LLM Benchmarking
|
||||
|
||||
## What's inside
|
||||
|
||||
Evaluates LLMs across 60+ academic benchmarks (MMLU, HumanEval, GSM8K, TruthfulQA, HellaSwag). Use when benchmarking model quality, comparing models, reporting academic results, or tracking training progress. Industry standard used by EleutherAI, HuggingFace, and major labs. Supports HuggingFace, vLLM, APIs.
|
||||
|
||||
## Quick start
|
||||
|
||||
lm-evaluation-harness evaluates LLMs across 60+ academic benchmarks using standardized prompts and metrics.
|
||||
|
||||
**Installation**:
|
||||
```bash
|
||||
pip install lm-eval
|
||||
```
|
||||
|
||||
**Evaluate any HuggingFace model**:
|
||||
```bash
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=meta-llama/Llama-2-7b-hf \
|
||||
--tasks mmlu,gsm8k,hellaswag \
|
||||
--device cuda:0 \
|
||||
--batch_size 8
|
||||
```
|
||||
|
||||
**View available tasks**:
|
||||
```bash
|
||||
lm-eval ls tasks
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: Standard benchmark evaluation
|
||||
|
||||
Evaluate model on core benchmarks (MMLU, GSM8K, HumanEval).
|
||||
|
||||
Copy this checklist:
|
||||
|
||||
```
|
||||
Benchmark Evaluation:
|
||||
- [ ] Step 1: Choose benchmark suite
|
||||
- [ ] Step 2: Configure model
|
||||
- [ ] Step 3: Run evaluation
|
||||
- [ ] Step 4: Analyze results
|
||||
```
|
||||
|
||||
**Step 1: Choose benchmark suite**
|
||||
|
||||
**Core reasoning benchmarks**:
|
||||
- **MMLU** (Massive Multitask Language Understanding) - 57 subjects, multiple choice
|
||||
- **GSM8K** - Grade school math word problems
|
||||
- **HellaSwag** - Common sense reasoning
|
||||
- **TruthfulQA** - Truthfulness and factuality
|
||||
- **ARC** (AI2 Reasoning Challenge) - Science questions
|
||||
|
||||
**Code benchmarks**:
|
||||
- **HumanEval** - Python code generation (164 problems)
|
||||
- **MBPP** (Mostly Basic Python Problems) - Python coding
|
||||
|
||||
**Standard suite** (recommended for model releases):
|
||||
```bash
|
||||
--tasks mmlu,gsm8k,hellaswag,truthfulqa,arc_challenge
|
||||
```
|
||||
|
||||
**Step 2: Configure model**
|
||||
|
||||
**HuggingFace model**:
|
||||
```bash
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=meta-llama/Llama-2-7b-hf,dtype=bfloat16 \
|
||||
--tasks mmlu \
|
||||
--device cuda:0 \
|
||||
--batch_size auto # Auto-detect optimal batch size
|
||||
```
|
||||
|
||||
**Quantized model (4-bit/8-bit)**:
|
||||
```bash
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=meta-llama/Llama-2-7b-hf,load_in_4bit=True \
|
||||
--tasks mmlu \
|
||||
--device cuda:0
|
||||
```
|
||||
|
||||
**Custom checkpoint**:
|
||||
```bash
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=/path/to/my-model,tokenizer=/path/to/tokenizer \
|
||||
--tasks mmlu \
|
||||
--device cuda:0
|
||||
```
|
||||
|
||||
**Step 3: Run evaluation**
|
||||
|
||||
```bash
|
||||
# Full MMLU evaluation (57 subjects)
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=meta-llama/Llama-2-7b-hf \
|
||||
--tasks mmlu \
|
||||
--num_fewshot 5 \ # 5-shot evaluation (standard)
|
||||
--batch_size 8 \
|
||||
--output_path results/ \
|
||||
--log_samples # Save individual predictions
|
||||
|
||||
# Multiple benchmarks at once
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=meta-llama/Llama-2-7b-hf \
|
||||
--tasks mmlu,gsm8k,hellaswag,truthfulqa,arc_challenge \
|
||||
--num_fewshot 5 \
|
||||
--batch_size 8 \
|
||||
--output_path results/llama2-7b-eval.json
|
||||
```
|
||||
|
||||
**Step 4: Analyze results**
|
||||
|
||||
Results saved to `results/llama2-7b-eval.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"results": {
|
||||
"mmlu": {
|
||||
"acc": 0.459,
|
||||
"acc_stderr": 0.004
|
||||
},
|
||||
"gsm8k": {
|
||||
"exact_match": 0.142,
|
||||
"exact_match_stderr": 0.006
|
||||
},
|
||||
"hellaswag": {
|
||||
"acc_norm": 0.765,
|
||||
"acc_norm_stderr": 0.004
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"model": "hf",
|
||||
"model_args": "pretrained=meta-llama/Llama-2-7b-hf",
|
||||
"num_fewshot": 5
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Workflow 2: Track training progress
|
||||
|
||||
Evaluate checkpoints during training.
|
||||
|
||||
```
|
||||
Training Progress Tracking:
|
||||
- [ ] Step 1: Set up periodic evaluation
|
||||
- [ ] Step 2: Choose quick benchmarks
|
||||
- [ ] Step 3: Automate evaluation
|
||||
- [ ] Step 4: Plot learning curves
|
||||
```
|
||||
|
||||
**Step 1: Set up periodic evaluation**
|
||||
|
||||
Evaluate every N training steps:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# eval_checkpoint.sh
|
||||
|
||||
CHECKPOINT_DIR=$1
|
||||
STEP=$2
|
||||
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=$CHECKPOINT_DIR/checkpoint-$STEP \
|
||||
--tasks gsm8k,hellaswag \
|
||||
--num_fewshot 0 \ # 0-shot for speed
|
||||
--batch_size 16 \
|
||||
--output_path results/step-$STEP.json
|
||||
```
|
||||
|
||||
**Step 2: Choose quick benchmarks**
|
||||
|
||||
Fast benchmarks for frequent evaluation:
|
||||
- **HellaSwag**: ~10 minutes on 1 GPU
|
||||
- **GSM8K**: ~5 minutes
|
||||
- **PIQA**: ~2 minutes
|
||||
|
||||
Avoid for frequent eval (too slow):
|
||||
- **MMLU**: ~2 hours (57 subjects)
|
||||
- **HumanEval**: Requires code execution
|
||||
|
||||
**Step 3: Automate evaluation**
|
||||
|
||||
Integrate with training script:
|
||||
|
||||
```python
|
||||
# In training loop
|
||||
if step % eval_interval == 0:
|
||||
model.save_pretrained(f"checkpoints/step-{step}")
|
||||
|
||||
# Run evaluation
|
||||
os.system(f"./eval_checkpoint.sh checkpoints step-{step}")
|
||||
```
|
||||
|
||||
Or use PyTorch Lightning callbacks:
|
||||
|
||||
```python
|
||||
from pytorch_lightning import Callback
|
||||
|
||||
class EvalHarnessCallback(Callback):
|
||||
def on_validation_epoch_end(self, trainer, pl_module):
|
||||
step = trainer.global_step
|
||||
checkpoint_path = f"checkpoints/step-{step}"
|
||||
|
||||
# Save checkpoint
|
||||
trainer.save_checkpoint(checkpoint_path)
|
||||
|
||||
# Run lm-eval
|
||||
os.system(f"lm_eval --model hf --model_args pretrained={checkpoint_path} ...")
|
||||
```
|
||||
|
||||
**Step 4: Plot learning curves**
|
||||
|
||||
```python
|
||||
import json
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# Load all results
|
||||
steps = []
|
||||
mmlu_scores = []
|
||||
|
||||
for file in sorted(glob.glob("results/step-*.json")):
|
||||
with open(file) as f:
|
||||
data = json.load(f)
|
||||
step = int(file.split("-")[1].split(".")[0])
|
||||
steps.append(step)
|
||||
mmlu_scores.append(data["results"]["mmlu"]["acc"])
|
||||
|
||||
# Plot
|
||||
plt.plot(steps, mmlu_scores)
|
||||
plt.xlabel("Training Step")
|
||||
plt.ylabel("MMLU Accuracy")
|
||||
plt.title("Training Progress")
|
||||
plt.savefig("training_curve.png")
|
||||
```
|
||||
|
||||
### Workflow 3: Compare multiple models
|
||||
|
||||
Benchmark suite for model comparison.
|
||||
|
||||
```
|
||||
Model Comparison:
|
||||
- [ ] Step 1: Define model list
|
||||
- [ ] Step 2: Run evaluations
|
||||
- [ ] Step 3: Generate comparison table
|
||||
```
|
||||
|
||||
**Step 1: Define model list**
|
||||
|
||||
```bash
|
||||
# models.txt
|
||||
meta-llama/Llama-2-7b-hf
|
||||
meta-llama/Llama-2-13b-hf
|
||||
mistralai/Mistral-7B-v0.1
|
||||
microsoft/phi-2
|
||||
```
|
||||
|
||||
**Step 2: Run evaluations**
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# eval_all_models.sh
|
||||
|
||||
TASKS="mmlu,gsm8k,hellaswag,truthfulqa"
|
||||
|
||||
while read model; do
|
||||
echo "Evaluating $model"
|
||||
|
||||
# Extract model name for output file
|
||||
model_name=$(echo $model | sed 's/\//-/g')
|
||||
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=$model,dtype=bfloat16 \
|
||||
--tasks $TASKS \
|
||||
--num_fewshot 5 \
|
||||
--batch_size auto \
|
||||
--output_path results/$model_name.json
|
||||
|
||||
done < models.txt
|
||||
```
|
||||
|
||||
**Step 3: Generate comparison table**
|
||||
|
||||
```python
|
||||
import json
|
||||
import pandas as pd
|
||||
|
||||
models = [
|
||||
"meta-llama-Llama-2-7b-hf",
|
||||
"meta-llama-Llama-2-13b-hf",
|
||||
"mistralai-Mistral-7B-v0.1",
|
||||
"microsoft-phi-2"
|
||||
]
|
||||
|
||||
tasks = ["mmlu", "gsm8k", "hellaswag", "truthfulqa"]
|
||||
|
||||
results = []
|
||||
for model in models:
|
||||
with open(f"results/{model}.json") as f:
|
||||
data = json.load(f)
|
||||
row = {"Model": model.replace("-", "/")}
|
||||
for task in tasks:
|
||||
# Get primary metric for each task
|
||||
metrics = data["results"][task]
|
||||
if "acc" in metrics:
|
||||
row[task.upper()] = f"{metrics['acc']:.3f}"
|
||||
elif "exact_match" in metrics:
|
||||
row[task.upper()] = f"{metrics['exact_match']:.3f}"
|
||||
results.append(row)
|
||||
|
||||
df = pd.DataFrame(results)
|
||||
print(df.to_markdown(index=False))
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
| Model | MMLU | GSM8K | HELLASWAG | TRUTHFULQA |
|
||||
|------------------------|-------|-------|-----------|------------|
|
||||
| meta-llama/Llama-2-7b | 0.459 | 0.142 | 0.765 | 0.391 |
|
||||
| meta-llama/Llama-2-13b | 0.549 | 0.287 | 0.801 | 0.430 |
|
||||
| mistralai/Mistral-7B | 0.626 | 0.395 | 0.812 | 0.428 |
|
||||
| microsoft/phi-2 | 0.560 | 0.613 | 0.682 | 0.447 |
|
||||
```
|
||||
|
||||
### Workflow 4: Evaluate with vLLM (faster inference)
|
||||
|
||||
Use vLLM backend for 5-10x faster evaluation.
|
||||
|
||||
```
|
||||
vLLM Evaluation:
|
||||
- [ ] Step 1: Install vLLM
|
||||
- [ ] Step 2: Configure vLLM backend
|
||||
- [ ] Step 3: Run evaluation
|
||||
```
|
||||
|
||||
**Step 1: Install vLLM**
|
||||
|
||||
```bash
|
||||
pip install vllm
|
||||
```
|
||||
|
||||
**Step 2: Configure vLLM backend**
|
||||
|
||||
```bash
|
||||
lm_eval --model vllm \
|
||||
--model_args pretrained=meta-llama/Llama-2-7b-hf,tensor_parallel_size=1,dtype=auto,gpu_memory_utilization=0.8 \
|
||||
--tasks mmlu \
|
||||
--batch_size auto
|
||||
```
|
||||
|
||||
**Step 3: Run evaluation**
|
||||
|
||||
vLLM is 5-10× faster than standard HuggingFace:
|
||||
|
||||
```bash
|
||||
# Standard HF: ~2 hours for MMLU on 7B model
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=meta-llama/Llama-2-7b-hf \
|
||||
--tasks mmlu \
|
||||
--batch_size 8
|
||||
|
||||
# vLLM: ~15-20 minutes for MMLU on 7B model
|
||||
lm_eval --model vllm \
|
||||
--model_args pretrained=meta-llama/Llama-2-7b-hf,tensor_parallel_size=2 \
|
||||
--tasks mmlu \
|
||||
--batch_size auto
|
||||
```
|
||||
|
||||
## When to use vs alternatives
|
||||
|
||||
**Use lm-evaluation-harness when:**
|
||||
- Benchmarking models for academic papers
|
||||
- Comparing model quality across standard tasks
|
||||
- Tracking training progress
|
||||
- Reporting standardized metrics (everyone uses same prompts)
|
||||
- Need reproducible evaluation
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **HELM** (Stanford): Broader evaluation (fairness, efficiency, calibration)
|
||||
- **AlpacaEval**: Instruction-following evaluation with LLM judges
|
||||
- **MT-Bench**: Conversational multi-turn evaluation
|
||||
- **Custom scripts**: Domain-specific evaluation
|
||||
|
||||
## Common issues
|
||||
|
||||
**Issue: Evaluation too slow**
|
||||
|
||||
Use vLLM backend:
|
||||
```bash
|
||||
lm_eval --model vllm \
|
||||
--model_args pretrained=model-name,tensor_parallel_size=2
|
||||
```
|
||||
|
||||
Or reduce fewshot examples:
|
||||
```bash
|
||||
--num_fewshot 0 # Instead of 5
|
||||
```
|
||||
|
||||
Or evaluate subset of MMLU:
|
||||
```bash
|
||||
--tasks mmlu_stem # Only STEM subjects
|
||||
```
|
||||
|
||||
**Issue: Out of memory**
|
||||
|
||||
Reduce batch size:
|
||||
```bash
|
||||
--batch_size 1 # Or --batch_size auto
|
||||
```
|
||||
|
||||
Use quantization:
|
||||
```bash
|
||||
--model_args pretrained=model-name,load_in_8bit=True
|
||||
```
|
||||
|
||||
Enable CPU offloading:
|
||||
```bash
|
||||
--model_args pretrained=model-name,device_map=auto,offload_folder=offload
|
||||
```
|
||||
|
||||
**Issue: Different results than reported**
|
||||
|
||||
Check fewshot count:
|
||||
```bash
|
||||
--num_fewshot 5 # Most papers use 5-shot
|
||||
```
|
||||
|
||||
Check exact task name:
|
||||
```bash
|
||||
--tasks mmlu # Not mmlu_direct or mmlu_fewshot
|
||||
```
|
||||
|
||||
Verify model and tokenizer match:
|
||||
```bash
|
||||
--model_args pretrained=model-name,tokenizer=same-model-name
|
||||
```
|
||||
|
||||
**Issue: HumanEval not executing code**
|
||||
|
||||
Code-executing tasks (HumanEval, MBPP, etc.) are gated behind an explicit
|
||||
confirmation flag — you must pass `--confirm_run_unsafe_code` to run them:
|
||||
|
||||
```bash
|
||||
lm_eval --model hf \
|
||||
--model_args pretrained=model-name \
|
||||
--tasks humaneval \
|
||||
--confirm_run_unsafe_code # Required to run tasks that execute generated code
|
||||
```
|
||||
|
||||
Without this flag lm-eval refuses to run the task rather than silently skipping
|
||||
code execution.
|
||||
|
||||
## Advanced topics
|
||||
|
||||
**Benchmark descriptions**: See [references/benchmark-guide.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\evaluation\evaluating-llms-harness/references/benchmark-guide.md) for detailed description of all 60+ tasks, what they measure, and interpretation.
|
||||
|
||||
**Custom tasks**: See [references/custom-tasks.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\evaluation\evaluating-llms-harness/references/custom-tasks.md) for creating domain-specific evaluation tasks.
|
||||
|
||||
**API evaluation**: See [references/api-evaluation.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\evaluation\evaluating-llms-harness/references/api-evaluation.md) for evaluating OpenAI, Anthropic, and other API models.
|
||||
|
||||
**Multi-GPU strategies**: See [references/distributed-eval.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\evaluation\evaluating-llms-harness/references/distributed-eval.md) for data parallel and tensor parallel evaluation.
|
||||
|
||||
## Hardware requirements
|
||||
|
||||
- **GPU**: NVIDIA (CUDA 11.8+), works on CPU (very slow)
|
||||
- **VRAM**:
|
||||
- 7B model: 16GB (bf16) or 8GB (8-bit)
|
||||
- 13B model: 28GB (bf16) or 14GB (8-bit)
|
||||
- 70B model: Requires multi-GPU or quantization
|
||||
- **Time** (7B model, single A100):
|
||||
- HellaSwag: 10 minutes
|
||||
- GSM8K: 5 minutes
|
||||
- MMLU (full): 2 hours
|
||||
- HumanEval: 20 minutes
|
||||
|
||||
## Resources
|
||||
|
||||
- GitHub: https://github.com/EleutherAI/lm-evaluation-harness
|
||||
- Docs: https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs
|
||||
- Task library: 60+ tasks including MMLU, GSM8K, HumanEval, TruthfulQA, HellaSwag, ARC, WinoGrande, etc.
|
||||
- Leaderboard: https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard (uses this harness)
|
||||
@@ -0,0 +1,613 @@
|
||||
---
|
||||
title: "Weights And Biases — W&B: log ML experiments, sweeps, model registry, dashboards"
|
||||
sidebar_label: "Weights And Biases"
|
||||
description: "W&B: log ML experiments, sweeps, model registry, dashboards"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Weights And Biases
|
||||
|
||||
W&B: log ML experiments, sweeps, model registry, dashboards.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/weights-and-biases` |
|
||||
| Path | `optional-skills/mlops\evaluation\weights-and-biases` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `wandb` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `MLOps`, `Weights And Biases`, `WandB`, `Experiment Tracking`, `Hyperparameter Tuning`, `Model Registry`, `Collaboration`, `Real-Time Visualization`, `PyTorch`, `TensorFlow`, `HuggingFace` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Weights & Biases: ML Experiment Tracking & MLOps
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use Weights & Biases (W&B) when you need to:
|
||||
- **Track ML experiments** with automatic metric logging
|
||||
- **Visualize training** in real-time dashboards
|
||||
- **Compare runs** across hyperparameters and configurations
|
||||
- **Optimize hyperparameters** with automated sweeps
|
||||
- **Manage model registry** with versioning and lineage
|
||||
- **Collaborate on ML projects** with team workspaces
|
||||
- **Track artifacts** (datasets, models, code) with lineage
|
||||
|
||||
**Users**: 200,000+ ML practitioners | **GitHub Stars**: 10.5k+ | **Integrations**: 100+
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Install W&B
|
||||
pip install wandb
|
||||
|
||||
# Login (creates API key)
|
||||
wandb login
|
||||
|
||||
# Or set API key programmatically
|
||||
export WANDB_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Basic Experiment Tracking
|
||||
|
||||
```python
|
||||
import wandb
|
||||
|
||||
# Initialize a run
|
||||
run = wandb.init(
|
||||
project="my-project",
|
||||
config={
|
||||
"learning_rate": 0.001,
|
||||
"epochs": 10,
|
||||
"batch_size": 32,
|
||||
"architecture": "ResNet50"
|
||||
}
|
||||
)
|
||||
|
||||
# Training loop
|
||||
for epoch in range(run.config.epochs):
|
||||
# Your training code
|
||||
train_loss = train_epoch()
|
||||
val_loss = validate()
|
||||
|
||||
# Log metrics
|
||||
wandb.log({
|
||||
"epoch": epoch,
|
||||
"train/loss": train_loss,
|
||||
"val/loss": val_loss,
|
||||
"train/accuracy": train_acc,
|
||||
"val/accuracy": val_acc
|
||||
})
|
||||
|
||||
# Finish the run
|
||||
wandb.finish()
|
||||
```
|
||||
|
||||
### With PyTorch
|
||||
|
||||
```python
|
||||
import torch
|
||||
import wandb
|
||||
|
||||
# Initialize
|
||||
wandb.init(project="pytorch-demo", config={
|
||||
"lr": 0.001,
|
||||
"epochs": 10
|
||||
})
|
||||
|
||||
# Access config
|
||||
config = wandb.config
|
||||
|
||||
# Training loop
|
||||
for epoch in range(config.epochs):
|
||||
for batch_idx, (data, target) in enumerate(train_loader):
|
||||
# Forward pass
|
||||
output = model(data)
|
||||
loss = criterion(output, target)
|
||||
|
||||
# Backward pass
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
# Log every 100 batches
|
||||
if batch_idx % 100 == 0:
|
||||
wandb.log({
|
||||
"loss": loss.item(),
|
||||
"epoch": epoch,
|
||||
"batch": batch_idx
|
||||
})
|
||||
|
||||
# Save model
|
||||
torch.save(model.state_dict(), "model.pth")
|
||||
wandb.save("model.pth") # Upload to W&B
|
||||
|
||||
wandb.finish()
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### 1. Projects and Runs
|
||||
|
||||
**Project**: Collection of related experiments
|
||||
**Run**: Single execution of your training script
|
||||
|
||||
```python
|
||||
# Create/use project
|
||||
run = wandb.init(
|
||||
project="image-classification",
|
||||
name="resnet50-experiment-1", # Optional run name
|
||||
tags=["baseline", "resnet"], # Organize with tags
|
||||
notes="First baseline run" # Add notes
|
||||
)
|
||||
|
||||
# Each run has unique ID
|
||||
print(f"Run ID: {run.id}")
|
||||
print(f"Run URL: {run.url}")
|
||||
```
|
||||
|
||||
### 2. Configuration Tracking
|
||||
|
||||
Track hyperparameters automatically:
|
||||
|
||||
```python
|
||||
config = {
|
||||
# Model architecture
|
||||
"model": "ResNet50",
|
||||
"pretrained": True,
|
||||
|
||||
# Training params
|
||||
"learning_rate": 0.001,
|
||||
"batch_size": 32,
|
||||
"epochs": 50,
|
||||
"optimizer": "Adam",
|
||||
|
||||
# Data params
|
||||
"dataset": "ImageNet",
|
||||
"augmentation": "standard"
|
||||
}
|
||||
|
||||
wandb.init(project="my-project", config=config)
|
||||
|
||||
# Access config during training
|
||||
lr = wandb.config.learning_rate
|
||||
batch_size = wandb.config.batch_size
|
||||
```
|
||||
|
||||
### 3. Metric Logging
|
||||
|
||||
```python
|
||||
# Log scalars
|
||||
wandb.log({"loss": 0.5, "accuracy": 0.92})
|
||||
|
||||
# Log multiple metrics
|
||||
wandb.log({
|
||||
"train/loss": train_loss,
|
||||
"train/accuracy": train_acc,
|
||||
"val/loss": val_loss,
|
||||
"val/accuracy": val_acc,
|
||||
"learning_rate": current_lr,
|
||||
"epoch": epoch
|
||||
})
|
||||
|
||||
# Log with custom x-axis
|
||||
wandb.log({"loss": loss}, step=global_step)
|
||||
|
||||
# Log media (images, audio, video)
|
||||
wandb.log({"examples": [wandb.Image(img) for img in images]})
|
||||
|
||||
# Log histograms
|
||||
wandb.log({"gradients": wandb.Histogram(gradients)})
|
||||
|
||||
# Log tables
|
||||
table = wandb.Table(columns=["id", "prediction", "ground_truth"])
|
||||
wandb.log({"predictions": table})
|
||||
```
|
||||
|
||||
### 4. Model Checkpointing
|
||||
|
||||
```python
|
||||
import torch
|
||||
import wandb
|
||||
|
||||
# Save model checkpoint
|
||||
checkpoint = {
|
||||
'epoch': epoch,
|
||||
'model_state_dict': model.state_dict(),
|
||||
'optimizer_state_dict': optimizer.state_dict(),
|
||||
'loss': loss,
|
||||
}
|
||||
|
||||
torch.save(checkpoint, 'checkpoint.pth')
|
||||
|
||||
# Upload to W&B
|
||||
wandb.save('checkpoint.pth')
|
||||
|
||||
# Or use Artifacts (recommended)
|
||||
artifact = wandb.Artifact('model', type='model')
|
||||
artifact.add_file('checkpoint.pth')
|
||||
wandb.log_artifact(artifact)
|
||||
```
|
||||
|
||||
## Hyperparameter Sweeps
|
||||
|
||||
Automatically search for optimal hyperparameters.
|
||||
|
||||
### Define Sweep Configuration
|
||||
|
||||
```python
|
||||
sweep_config = {
|
||||
'method': 'bayes', # or 'grid', 'random'
|
||||
'metric': {
|
||||
'name': 'val/accuracy',
|
||||
'goal': 'maximize'
|
||||
},
|
||||
'parameters': {
|
||||
'learning_rate': {
|
||||
'distribution': 'log_uniform_values',
|
||||
'min': 1e-5,
|
||||
'max': 1e-1
|
||||
},
|
||||
'batch_size': {
|
||||
'values': [16, 32, 64, 128]
|
||||
},
|
||||
'optimizer': {
|
||||
'values': ['adam', 'sgd', 'rmsprop']
|
||||
},
|
||||
'dropout': {
|
||||
'distribution': 'uniform',
|
||||
'min': 0.1,
|
||||
'max': 0.5
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Initialize sweep
|
||||
sweep_id = wandb.sweep(sweep_config, project="my-project")
|
||||
```
|
||||
|
||||
### Define Training Function
|
||||
|
||||
```python
|
||||
def train():
|
||||
# Initialize run
|
||||
run = wandb.init()
|
||||
|
||||
# Access sweep parameters
|
||||
lr = wandb.config.learning_rate
|
||||
batch_size = wandb.config.batch_size
|
||||
optimizer_name = wandb.config.optimizer
|
||||
|
||||
# Build model with sweep config
|
||||
model = build_model(wandb.config)
|
||||
optimizer = get_optimizer(optimizer_name, lr)
|
||||
|
||||
# Training loop
|
||||
for epoch in range(NUM_EPOCHS):
|
||||
train_loss = train_epoch(model, optimizer, batch_size)
|
||||
val_acc = validate(model)
|
||||
|
||||
# Log metrics
|
||||
wandb.log({
|
||||
"train/loss": train_loss,
|
||||
"val/accuracy": val_acc
|
||||
})
|
||||
|
||||
# Run sweep
|
||||
wandb.agent(sweep_id, function=train, count=50) # Run 50 trials
|
||||
```
|
||||
|
||||
### Sweep Strategies
|
||||
|
||||
```python
|
||||
# Grid search - exhaustive
|
||||
sweep_config = {
|
||||
'method': 'grid',
|
||||
'parameters': {
|
||||
'lr': {'values': [0.001, 0.01, 0.1]},
|
||||
'batch_size': {'values': [16, 32, 64]}
|
||||
}
|
||||
}
|
||||
|
||||
# Random search
|
||||
sweep_config = {
|
||||
'method': 'random',
|
||||
'parameters': {
|
||||
'lr': {'distribution': 'uniform', 'min': 0.0001, 'max': 0.1},
|
||||
'dropout': {'distribution': 'uniform', 'min': 0.1, 'max': 0.5}
|
||||
}
|
||||
}
|
||||
|
||||
# Bayesian optimization (recommended)
|
||||
sweep_config = {
|
||||
'method': 'bayes',
|
||||
'metric': {'name': 'val/loss', 'goal': 'minimize'},
|
||||
'parameters': {
|
||||
'lr': {'distribution': 'log_uniform_values', 'min': 1e-5, 'max': 1e-1}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Artifacts
|
||||
|
||||
Track datasets, models, and other files with lineage.
|
||||
|
||||
### Log Artifacts
|
||||
|
||||
```python
|
||||
# Create artifact
|
||||
artifact = wandb.Artifact(
|
||||
name='training-dataset',
|
||||
type='dataset',
|
||||
description='ImageNet training split',
|
||||
metadata={'size': '1.2M images', 'split': 'train'}
|
||||
)
|
||||
|
||||
# Add files
|
||||
artifact.add_file('data/train.csv')
|
||||
artifact.add_dir('data/images/')
|
||||
|
||||
# Log artifact
|
||||
wandb.log_artifact(artifact)
|
||||
```
|
||||
|
||||
### Use Artifacts
|
||||
|
||||
```python
|
||||
# Download and use artifact
|
||||
run = wandb.init(project="my-project")
|
||||
|
||||
# Download artifact
|
||||
artifact = run.use_artifact('training-dataset:latest')
|
||||
artifact_dir = artifact.download()
|
||||
|
||||
# Use the data
|
||||
data = load_data(f"{artifact_dir}/train.csv")
|
||||
```
|
||||
|
||||
### Model Registry
|
||||
|
||||
```python
|
||||
# Log model as artifact
|
||||
model_artifact = wandb.Artifact(
|
||||
name='resnet50-model',
|
||||
type='model',
|
||||
metadata={'architecture': 'ResNet50', 'accuracy': 0.95}
|
||||
)
|
||||
|
||||
model_artifact.add_file('model.pth')
|
||||
wandb.log_artifact(model_artifact, aliases=['best', 'production'])
|
||||
|
||||
# Link to model registry
|
||||
run.link_artifact(model_artifact, 'model-registry/production-models')
|
||||
```
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### HuggingFace Transformers
|
||||
|
||||
```python
|
||||
from transformers import Trainer, TrainingArguments
|
||||
import wandb
|
||||
|
||||
# Initialize W&B
|
||||
wandb.init(project="hf-transformers")
|
||||
|
||||
# Training arguments with W&B
|
||||
training_args = TrainingArguments(
|
||||
output_dir="./results",
|
||||
report_to="wandb", # Enable W&B logging
|
||||
run_name="bert-finetuning",
|
||||
logging_steps=100,
|
||||
save_steps=500
|
||||
)
|
||||
|
||||
# Trainer automatically logs to W&B
|
||||
trainer = Trainer(
|
||||
model=model,
|
||||
args=training_args,
|
||||
train_dataset=train_dataset,
|
||||
eval_dataset=eval_dataset
|
||||
)
|
||||
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
### PyTorch Lightning
|
||||
|
||||
```python
|
||||
from pytorch_lightning import Trainer
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
import wandb
|
||||
|
||||
# Create W&B logger
|
||||
wandb_logger = WandbLogger(
|
||||
project="lightning-demo",
|
||||
log_model=True # Log model checkpoints
|
||||
)
|
||||
|
||||
# Use with Trainer
|
||||
trainer = Trainer(
|
||||
logger=wandb_logger,
|
||||
max_epochs=10
|
||||
)
|
||||
|
||||
trainer.fit(model, datamodule=dm)
|
||||
```
|
||||
|
||||
### Keras/TensorFlow
|
||||
|
||||
```python
|
||||
import wandb
|
||||
from wandb.integration.keras import WandbMetricsLogger, WandbModelCheckpoint
|
||||
|
||||
# Initialize
|
||||
wandb.init(project="keras-demo")
|
||||
|
||||
# Add callbacks (the monolithic WandbCallback was removed;
|
||||
# use the dedicated callbacks from wandb.integration.keras instead)
|
||||
model.fit(
|
||||
x_train, y_train,
|
||||
validation_data=(x_val, y_val),
|
||||
epochs=10,
|
||||
callbacks=[
|
||||
WandbMetricsLogger(), # Auto-logs metrics
|
||||
WandbModelCheckpoint("models/model-{epoch}") # Saves checkpoints
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Visualization & Analysis
|
||||
|
||||
### Custom Charts
|
||||
|
||||
```python
|
||||
# Log custom visualizations
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
fig, ax = plt.subplots()
|
||||
ax.plot(x, y)
|
||||
wandb.log({"custom_plot": wandb.Image(fig)})
|
||||
|
||||
# Log confusion matrix
|
||||
wandb.log({"conf_mat": wandb.plot.confusion_matrix(
|
||||
probs=None,
|
||||
y_true=ground_truth,
|
||||
preds=predictions,
|
||||
class_names=class_names
|
||||
)})
|
||||
```
|
||||
|
||||
### Reports
|
||||
|
||||
Create shareable reports in W&B UI:
|
||||
- Combine runs, charts, and text
|
||||
- Markdown support
|
||||
- Embeddable visualizations
|
||||
- Team collaboration
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Organize with Tags and Groups
|
||||
|
||||
```python
|
||||
wandb.init(
|
||||
project="my-project",
|
||||
tags=["baseline", "resnet50", "imagenet"],
|
||||
group="resnet-experiments", # Group related runs
|
||||
job_type="train" # Type of job
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Log Everything Relevant
|
||||
|
||||
```python
|
||||
# Log system metrics
|
||||
wandb.log({
|
||||
"gpu/util": gpu_utilization,
|
||||
"gpu/memory": gpu_memory_used,
|
||||
"cpu/util": cpu_utilization
|
||||
})
|
||||
|
||||
# Log code version
|
||||
wandb.log({"git_commit": git_commit_hash})
|
||||
|
||||
# Log data splits
|
||||
wandb.log({
|
||||
"data/train_size": len(train_dataset),
|
||||
"data/val_size": len(val_dataset)
|
||||
})
|
||||
```
|
||||
|
||||
### 3. Use Descriptive Names
|
||||
|
||||
```python
|
||||
# ✅ Good: Descriptive run names
|
||||
wandb.init(
|
||||
project="nlp-classification",
|
||||
name="bert-base-lr0.001-bs32-epoch10"
|
||||
)
|
||||
|
||||
# ❌ Bad: Generic names
|
||||
wandb.init(project="nlp", name="run1")
|
||||
```
|
||||
|
||||
### 4. Save Important Artifacts
|
||||
|
||||
```python
|
||||
# Save final model
|
||||
artifact = wandb.Artifact('final-model', type='model')
|
||||
artifact.add_file('model.pth')
|
||||
wandb.log_artifact(artifact)
|
||||
|
||||
# Save predictions for analysis
|
||||
predictions_table = wandb.Table(
|
||||
columns=["id", "input", "prediction", "ground_truth"],
|
||||
data=predictions_data
|
||||
)
|
||||
wandb.log({"predictions": predictions_table})
|
||||
```
|
||||
|
||||
### 5. Use Offline Mode for Unstable Connections
|
||||
|
||||
```python
|
||||
import os
|
||||
|
||||
# Enable offline mode
|
||||
os.environ["WANDB_MODE"] = "offline"
|
||||
|
||||
wandb.init(project="my-project")
|
||||
# ... your code ...
|
||||
|
||||
# Sync later
|
||||
# wandb sync <run_directory>
|
||||
```
|
||||
|
||||
## Team Collaboration
|
||||
|
||||
### Share Runs
|
||||
|
||||
```python
|
||||
# Runs are automatically shareable via URL
|
||||
run = wandb.init(project="team-project")
|
||||
print(f"Share this URL: {run.url}")
|
||||
```
|
||||
|
||||
### Team Projects
|
||||
|
||||
- Create team account at wandb.ai
|
||||
- Add team members
|
||||
- Set project visibility (private/public)
|
||||
- Use team-level artifacts and model registry
|
||||
|
||||
## Pricing
|
||||
|
||||
- **Free**: Unlimited public projects, 100GB storage
|
||||
- **Academic**: Free for students/researchers
|
||||
- **Teams**: $50/seat/month, private projects, unlimited storage
|
||||
- **Enterprise**: Custom pricing, on-prem options
|
||||
|
||||
## Resources
|
||||
|
||||
- **Documentation**: https://docs.wandb.ai
|
||||
- **GitHub**: https://github.com/wandb/wandb (10.5k+ stars)
|
||||
- **Examples**: https://github.com/wandb/examples
|
||||
- **Community**: https://wandb.ai/community
|
||||
- **Discord**: https://wandb.me/discord
|
||||
|
||||
## See Also
|
||||
|
||||
- `references/sweeps.md` - Comprehensive hyperparameter optimization guide
|
||||
- `references/artifacts.md` - Data and model versioning patterns
|
||||
- `references/integrations.md` - Framework-specific examples
|
||||
@@ -0,0 +1,240 @@
|
||||
---
|
||||
title: "Faiss — Fast vector similarity search at billion scale"
|
||||
sidebar_label: "Faiss"
|
||||
description: "Fast vector similarity search at billion scale"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Faiss
|
||||
|
||||
Fast vector similarity search at billion scale.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/faiss` |
|
||||
| Path | `optional-skills/mlops\faiss` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `faiss-cpu`, `faiss-gpu`, `numpy` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `RAG`, `FAISS`, `Similarity Search`, `Vector Search`, `Facebook AI`, `GPU Acceleration`, `Billion-Scale`, `K-NN`, `HNSW`, `High Performance`, `Large Scale` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# FAISS - Efficient Similarity Search
|
||||
|
||||
Facebook AI's library for billion-scale vector similarity search.
|
||||
|
||||
## When to use FAISS
|
||||
|
||||
**Use FAISS when:**
|
||||
- Need fast similarity search on large vector datasets (millions/billions)
|
||||
- GPU acceleration required
|
||||
- Pure vector similarity (no metadata filtering needed)
|
||||
- High throughput, low latency critical
|
||||
- Offline/batch processing of embeddings
|
||||
|
||||
**Metrics**:
|
||||
- **31,700+ GitHub stars**
|
||||
- Meta/Facebook AI Research
|
||||
- **Handles billions of vectors**
|
||||
- **C++** with Python bindings
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **Chroma/Pinecone**: Need metadata filtering
|
||||
- **Weaviate**: Need full database features
|
||||
- **Annoy**: Simpler, fewer features
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# CPU only
|
||||
pip install faiss-cpu
|
||||
|
||||
# GPU support
|
||||
pip install faiss-gpu
|
||||
```
|
||||
|
||||
### Basic usage
|
||||
|
||||
```python
|
||||
import faiss
|
||||
import numpy as np
|
||||
|
||||
# Create sample data (1000 vectors, 128 dimensions)
|
||||
d = 128
|
||||
nb = 1000
|
||||
vectors = np.random.random((nb, d)).astype('float32')
|
||||
|
||||
# Create index
|
||||
index = faiss.IndexFlatL2(d) # L2 distance
|
||||
index.add(vectors) # Add vectors
|
||||
|
||||
# Search
|
||||
k = 5 # Find 5 nearest neighbors
|
||||
query = np.random.random((1, d)).astype('float32')
|
||||
distances, indices = index.search(query, k)
|
||||
|
||||
print(f"Nearest neighbors: {indices}")
|
||||
print(f"Distances: {distances}")
|
||||
```
|
||||
|
||||
## Index types
|
||||
|
||||
### 1. Flat (exact search)
|
||||
|
||||
```python
|
||||
# L2 (Euclidean) distance
|
||||
index = faiss.IndexFlatL2(d)
|
||||
|
||||
# Inner product (cosine similarity if normalized)
|
||||
index = faiss.IndexFlatIP(d)
|
||||
|
||||
# Slowest, most accurate
|
||||
```
|
||||
|
||||
### 2. IVF (inverted file) - Fast approximate
|
||||
|
||||
```python
|
||||
# Create quantizer
|
||||
quantizer = faiss.IndexFlatL2(d)
|
||||
|
||||
# IVF index with 100 clusters
|
||||
nlist = 100
|
||||
index = faiss.IndexIVFFlat(quantizer, d, nlist)
|
||||
|
||||
# Train on data
|
||||
index.train(vectors)
|
||||
|
||||
# Add vectors
|
||||
index.add(vectors)
|
||||
|
||||
# Search (nprobe = clusters to search)
|
||||
index.nprobe = 10
|
||||
distances, indices = index.search(query, k)
|
||||
```
|
||||
|
||||
### 3. HNSW (Hierarchical NSW) - Best quality/speed
|
||||
|
||||
```python
|
||||
# HNSW index
|
||||
M = 32 # Number of connections per layer
|
||||
index = faiss.IndexHNSWFlat(d, M)
|
||||
|
||||
# No training needed
|
||||
index.add(vectors)
|
||||
|
||||
# Search
|
||||
distances, indices = index.search(query, k)
|
||||
```
|
||||
|
||||
### 4. Product Quantization - Memory efficient
|
||||
|
||||
```python
|
||||
# PQ reduces memory by 16-32×
|
||||
m = 8 # Number of subquantizers
|
||||
nbits = 8
|
||||
index = faiss.IndexPQ(d, m, nbits)
|
||||
|
||||
# Train and add
|
||||
index.train(vectors)
|
||||
index.add(vectors)
|
||||
```
|
||||
|
||||
## Save and load
|
||||
|
||||
```python
|
||||
# Save index
|
||||
faiss.write_index(index, "large.index")
|
||||
|
||||
# Load index
|
||||
index = faiss.read_index("large.index")
|
||||
|
||||
# Continue using
|
||||
distances, indices = index.search(query, k)
|
||||
```
|
||||
|
||||
## GPU acceleration
|
||||
|
||||
```python
|
||||
# Single GPU
|
||||
res = faiss.StandardGpuResources()
|
||||
index_cpu = faiss.IndexFlatL2(d)
|
||||
index_gpu = faiss.index_cpu_to_gpu(res, 0, index_cpu) # GPU 0
|
||||
|
||||
# Multi-GPU
|
||||
index_gpu = faiss.index_cpu_to_all_gpus(index_cpu)
|
||||
|
||||
# 10-100× faster than CPU
|
||||
```
|
||||
|
||||
## LangChain integration
|
||||
|
||||
```python
|
||||
from langchain_community.vectorstores import FAISS
|
||||
from langchain_openai import OpenAIEmbeddings
|
||||
|
||||
# Create FAISS vector store
|
||||
vectorstore = FAISS.from_documents(docs, OpenAIEmbeddings())
|
||||
|
||||
# Save
|
||||
vectorstore.save_local("faiss_index")
|
||||
|
||||
# Load
|
||||
vectorstore = FAISS.load_local(
|
||||
"faiss_index",
|
||||
OpenAIEmbeddings(),
|
||||
allow_dangerous_deserialization=True
|
||||
)
|
||||
|
||||
# Search
|
||||
results = vectorstore.similarity_search("query", k=5)
|
||||
```
|
||||
|
||||
## LlamaIndex integration
|
||||
|
||||
```python
|
||||
from llama_index.vector_stores.faiss import FaissVectorStore
|
||||
import faiss
|
||||
|
||||
# Create FAISS index
|
||||
d = 1536
|
||||
faiss_index = faiss.IndexFlatL2(d)
|
||||
|
||||
vector_store = FaissVectorStore(faiss_index=faiss_index)
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
1. **Choose right index type** - Flat for <10K, IVF for 10K-1M, HNSW for quality
|
||||
2. **Normalize for cosine** - Use IndexFlatIP with normalized vectors
|
||||
3. **Use GPU for large datasets** - 10-100× faster
|
||||
4. **Save trained indices** - Training is expensive
|
||||
5. **Tune nprobe/ef_search** - Balance speed/accuracy
|
||||
6. **Monitor memory** - PQ for large datasets
|
||||
7. **Batch queries** - Better GPU utilization
|
||||
|
||||
## Performance
|
||||
|
||||
| Index Type | Build Time | Search Time | Memory | Accuracy |
|
||||
|------------|------------|-------------|--------|----------|
|
||||
| Flat | Fast | Slow | High | 100% |
|
||||
| IVF | Medium | Fast | Medium | 95-99% |
|
||||
| HNSW | Slow | Fastest | High | 99% |
|
||||
| PQ | Medium | Fast | Low | 90-95% |
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/facebookresearch/faiss ⭐ 31,700+
|
||||
- **Wiki**: https://github.com/facebookresearch/faiss/wiki
|
||||
- **License**: MIT
|
||||
@@ -0,0 +1,388 @@
|
||||
---
|
||||
title: "Flash Attention — Speed up long-sequence transformer training and inference"
|
||||
sidebar_label: "Flash Attention"
|
||||
description: "Speed up long-sequence transformer training and inference"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Flash Attention
|
||||
|
||||
Speed up long-sequence transformer training and inference.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/flash-attention` |
|
||||
| Path | `optional-skills/mlops\flash-attention` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `flash-attn`, `torch`, `transformers` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Optimization`, `Flash Attention`, `Attention Optimization`, `Memory Efficiency`, `Speed Optimization`, `Long Context`, `PyTorch`, `SDPA`, `H100`, `FP8`, `Transformers` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Flash Attention - Fast Memory-Efficient Attention
|
||||
|
||||
## Quick start
|
||||
|
||||
Flash Attention provides 2-4x speedup and 10-20x memory reduction for transformer attention through IO-aware tiling and recomputation.
|
||||
|
||||
**PyTorch native (easiest, PyTorch 2.2+)**:
|
||||
```python
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
q = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16) # [batch, heads, seq, dim]
|
||||
k = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)
|
||||
v = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)
|
||||
|
||||
# Automatically uses Flash Attention if available
|
||||
out = F.scaled_dot_product_attention(q, k, v)
|
||||
```
|
||||
|
||||
**flash-attn library (more features)**:
|
||||
```bash
|
||||
pip install flash-attn --no-build-isolation
|
||||
```
|
||||
|
||||
```python
|
||||
from flash_attn import flash_attn_func
|
||||
|
||||
# q, k, v: [batch, seqlen, nheads, headdim]
|
||||
out = flash_attn_func(q, k, v, dropout_p=0.0, causal=True)
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: Enable in existing PyTorch model
|
||||
|
||||
Copy this checklist:
|
||||
|
||||
```
|
||||
Flash Attention Integration:
|
||||
- [ ] Step 1: Check PyTorch version (≥2.2)
|
||||
- [ ] Step 2: Enable Flash Attention backend
|
||||
- [ ] Step 3: Verify speedup with profiling
|
||||
- [ ] Step 4: Test accuracy matches baseline
|
||||
```
|
||||
|
||||
**Step 1: Check PyTorch version**
|
||||
|
||||
```bash
|
||||
python -c "import torch; print(torch.__version__)"
|
||||
# Should be ≥2.2.0
|
||||
```
|
||||
|
||||
If <2.2, upgrade:
|
||||
```bash
|
||||
pip install --upgrade torch
|
||||
```
|
||||
|
||||
**Step 2: Enable Flash Attention backend**
|
||||
|
||||
Replace standard attention:
|
||||
```python
|
||||
# Before (standard attention)
|
||||
attn_weights = torch.softmax(q @ k.transpose(-2, -1) / math.sqrt(d_k), dim=-1)
|
||||
out = attn_weights @ v
|
||||
|
||||
# After (Flash Attention)
|
||||
import torch.nn.functional as F
|
||||
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
||||
```
|
||||
|
||||
Force Flash Attention backend (`torch.backends.cuda.sdp_kernel` is deprecated; use
|
||||
`torch.nn.attention.sdpa_kernel` with `SDPBackend`):
|
||||
```python
|
||||
from torch.nn.attention import SDPBackend, sdpa_kernel
|
||||
|
||||
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
|
||||
out = F.scaled_dot_product_attention(q, k, v)
|
||||
```
|
||||
|
||||
**Step 3: Verify speedup with profiling**
|
||||
|
||||
```python
|
||||
import torch.utils.benchmark as benchmark
|
||||
|
||||
def test_attention(use_flash):
|
||||
q, k, v = [torch.randn(2, 8, 2048, 64, device='cuda', dtype=torch.float16) for _ in range(3)]
|
||||
|
||||
if use_flash:
|
||||
from torch.nn.attention import SDPBackend, sdpa_kernel
|
||||
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
|
||||
return F.scaled_dot_product_attention(q, k, v)
|
||||
else:
|
||||
attn = (q @ k.transpose(-2, -1) / 8.0).softmax(dim=-1)
|
||||
return attn @ v
|
||||
|
||||
# Benchmark
|
||||
t_flash = benchmark.Timer(stmt='test_attention(True)', globals=globals())
|
||||
t_standard = benchmark.Timer(stmt='test_attention(False)', globals=globals())
|
||||
|
||||
print(f"Flash: {t_flash.timeit(100).mean:.3f}s")
|
||||
print(f"Standard: {t_standard.timeit(100).mean:.3f}s")
|
||||
```
|
||||
|
||||
Expected: 2-4x speedup for sequences >512 tokens.
|
||||
|
||||
**Step 4: Test accuracy matches baseline**
|
||||
|
||||
```python
|
||||
# Compare outputs
|
||||
q, k, v = [torch.randn(1, 8, 512, 64, device='cuda', dtype=torch.float16) for _ in range(3)]
|
||||
|
||||
# Flash Attention
|
||||
out_flash = F.scaled_dot_product_attention(q, k, v)
|
||||
|
||||
# Standard attention
|
||||
attn_weights = torch.softmax(q @ k.transpose(-2, -1) / 8.0, dim=-1)
|
||||
out_standard = attn_weights @ v
|
||||
|
||||
# Check difference
|
||||
diff = (out_flash - out_standard).abs().max()
|
||||
print(f"Max difference: {diff:.6f}")
|
||||
# Should be <1e-3 for float16
|
||||
```
|
||||
|
||||
### Workflow 2: Use flash-attn library for advanced features
|
||||
|
||||
For multi-query attention, sliding window, or H100 FP8.
|
||||
|
||||
Copy this checklist:
|
||||
|
||||
```
|
||||
flash-attn Library Setup:
|
||||
- [ ] Step 1: Install flash-attn library
|
||||
- [ ] Step 2: Modify attention code
|
||||
- [ ] Step 3: Enable advanced features
|
||||
- [ ] Step 4: Benchmark performance
|
||||
```
|
||||
|
||||
**Step 1: Install flash-attn library**
|
||||
|
||||
```bash
|
||||
# NVIDIA GPUs (CUDA 12.0+)
|
||||
pip install flash-attn --no-build-isolation
|
||||
|
||||
# Verify installation
|
||||
python -c "from flash_attn import flash_attn_func; print('Success')"
|
||||
```
|
||||
|
||||
**Step 2: Modify attention code**
|
||||
|
||||
```python
|
||||
from flash_attn import flash_attn_func
|
||||
|
||||
# Input: [batch_size, seq_len, num_heads, head_dim]
|
||||
# Transpose from [batch, heads, seq, dim] if needed
|
||||
q = q.transpose(1, 2) # [batch, seq, heads, dim]
|
||||
k = k.transpose(1, 2)
|
||||
v = v.transpose(1, 2)
|
||||
|
||||
out = flash_attn_func(
|
||||
q, k, v,
|
||||
dropout_p=0.1,
|
||||
causal=True, # For autoregressive models
|
||||
window_size=(-1, -1), # No sliding window
|
||||
softmax_scale=None # Auto-scale
|
||||
)
|
||||
|
||||
out = out.transpose(1, 2) # Back to [batch, heads, seq, dim]
|
||||
```
|
||||
|
||||
**Step 3: Enable advanced features**
|
||||
|
||||
Multi-query attention (shared K/V across heads):
|
||||
```python
|
||||
from flash_attn import flash_attn_func
|
||||
|
||||
# q: [batch, seq, num_q_heads, dim]
|
||||
# k, v: [batch, seq, num_kv_heads, dim] # Fewer KV heads
|
||||
out = flash_attn_func(q, k, v) # Automatically handles MQA
|
||||
```
|
||||
|
||||
Sliding window attention (local attention):
|
||||
```python
|
||||
# Only attend to window of 256 tokens before/after
|
||||
out = flash_attn_func(
|
||||
q, k, v,
|
||||
window_size=(256, 256), # (left, right) window
|
||||
causal=True
|
||||
)
|
||||
```
|
||||
|
||||
**Step 4: Benchmark performance**
|
||||
|
||||
```python
|
||||
import torch
|
||||
from flash_attn import flash_attn_func
|
||||
import time
|
||||
|
||||
q, k, v = [torch.randn(4, 4096, 32, 64, device='cuda', dtype=torch.float16) for _ in range(3)]
|
||||
|
||||
# Warmup
|
||||
for _ in range(10):
|
||||
_ = flash_attn_func(q, k, v)
|
||||
|
||||
# Benchmark
|
||||
torch.cuda.synchronize()
|
||||
start = time.time()
|
||||
for _ in range(100):
|
||||
out = flash_attn_func(q, k, v)
|
||||
torch.cuda.synchronize()
|
||||
end = time.time()
|
||||
|
||||
print(f"Time per iteration: {(end-start)/100*1000:.2f}ms")
|
||||
print(f"Memory allocated: {torch.cuda.max_memory_allocated()/1e9:.2f}GB")
|
||||
```
|
||||
|
||||
### Workflow 3: H100 FP8 optimization (FlashAttention-3)
|
||||
|
||||
For maximum performance on Hopper GPUs (H100).
|
||||
|
||||
> **Important:** The pip package `flash-attn` (2.8.x) ships **FlashAttention-2 only** — it does
|
||||
> **not** contain FA3 or FP8 H100 kernels, and `flash_attn_func` does **not** auto-use FP8.
|
||||
> FlashAttention-3 is a separate **beta** build compiled from source from the repo's `hopper/`
|
||||
> directory, exposed via the `flash_attn_interface` module. FA3 supports FP16/BF16 forward+backward
|
||||
> and **FP8 forward only**.
|
||||
|
||||
```
|
||||
FP8 Setup:
|
||||
- [ ] Step 1: Verify Hopper (H100) GPU available
|
||||
- [ ] Step 2: Build & install FlashAttention-3 from source (hopper/)
|
||||
- [ ] Step 3: Use the FA3 interface (FP8 forward)
|
||||
```
|
||||
|
||||
**Step 1: Verify H100 GPU**
|
||||
|
||||
```bash
|
||||
nvidia-smi --query-gpu=name --format=csv
|
||||
# Should show "H100" or "H800"
|
||||
```
|
||||
|
||||
**Step 2: Build & install FlashAttention-3 from source**
|
||||
|
||||
FA3 is NOT included in `pip install flash-attn`. Build it from the `hopper/` subdirectory:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Dao-AILab/flash-attention.git
|
||||
cd flash-attention/hopper
|
||||
python setup.py install
|
||||
# (compilation is heavy and requires a CUDA toolchain + Hopper GPU)
|
||||
```
|
||||
|
||||
**Step 3: Use the FA3 interface (FP8 forward)**
|
||||
|
||||
FA3 exposes its own module `flash_attn_interface` (distinct from the FA2 `flash_attn`).
|
||||
FP8 is a **forward-only** path and expects `float8_e4m3fn` inputs:
|
||||
|
||||
```python
|
||||
import torch
|
||||
from flash_attn_interface import flash_attn_func # FA3 (hopper build), not `flash_attn`
|
||||
|
||||
# q, k, v: [batch, seqlen, nheads, headdim]
|
||||
q = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)
|
||||
k = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)
|
||||
v = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)
|
||||
|
||||
# FP8 forward (inference / forward-only): cast to float8_e4m3fn
|
||||
q_fp8 = q.to(torch.float8_e4m3fn)
|
||||
k_fp8 = k.to(torch.float8_e4m3fn)
|
||||
v_fp8 = v.to(torch.float8_e4m3fn)
|
||||
|
||||
out = flash_attn_func(q_fp8, k_fp8, v_fp8, causal=True)
|
||||
# FP16/BF16 forward+backward is also supported by the FA3 interface.
|
||||
```
|
||||
|
||||
## When to use vs alternatives
|
||||
|
||||
**Use Flash Attention when:**
|
||||
- Training transformers with sequences >512 tokens
|
||||
- Running inference with long context (>2K tokens)
|
||||
- GPU memory constrained (OOM with standard attention)
|
||||
- Need 2-4x speedup without accuracy loss
|
||||
- Using PyTorch 2.2+ or can install flash-attn
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **Standard attention**: Sequences <256 tokens (overhead not worth it)
|
||||
- **xFormers**: Need more attention variants (not just speed)
|
||||
- **Memory-efficient attention**: CPU inference (Flash Attention needs GPU)
|
||||
|
||||
## Common issues
|
||||
|
||||
**Issue: ImportError: cannot import flash_attn**
|
||||
|
||||
Install with no-build-isolation flag:
|
||||
```bash
|
||||
pip install flash-attn --no-build-isolation
|
||||
```
|
||||
|
||||
Or install CUDA toolkit first:
|
||||
```bash
|
||||
conda install cuda -c nvidia
|
||||
pip install flash-attn --no-build-isolation
|
||||
```
|
||||
|
||||
**Issue: Slower than expected (no speedup)**
|
||||
|
||||
Flash Attention benefits increase with sequence length:
|
||||
- <512 tokens: Minimal speedup (10-20%)
|
||||
- 512-2K tokens: 2-3x speedup
|
||||
- >2K tokens: 3-4x speedup
|
||||
|
||||
Check sequence length is sufficient.
|
||||
|
||||
**Issue: RuntimeError: CUDA error**
|
||||
|
||||
Verify GPU supports Flash Attention:
|
||||
```python
|
||||
import torch
|
||||
print(torch.cuda.get_device_capability())
|
||||
# Should be ≥(7, 5) for Turing+
|
||||
```
|
||||
|
||||
Flash Attention requires:
|
||||
- Ampere (A100, A10): ✅ Full support
|
||||
- Turing (T4): ✅ Supported
|
||||
- Volta (V100): ❌ Not supported
|
||||
|
||||
**Issue: Accuracy degradation**
|
||||
|
||||
Check dtype is float16 or bfloat16 (not float32):
|
||||
```python
|
||||
q = q.to(torch.float16) # Or torch.bfloat16
|
||||
```
|
||||
|
||||
Flash Attention uses float16/bfloat16 for speed. Float32 not supported.
|
||||
|
||||
## Advanced topics
|
||||
|
||||
**Integration with HuggingFace Transformers**: See [references/transformers-integration.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\flash-attention/references/transformers-integration.md) for enabling Flash Attention in BERT, GPT, Llama models.
|
||||
|
||||
**Performance benchmarks**: See [references/benchmarks.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\flash-attention/references/benchmarks.md) for detailed speed and memory comparisons across GPUs and sequence lengths.
|
||||
|
||||
## Hardware requirements
|
||||
|
||||
- **GPU**: NVIDIA Ampere+ (A100, A10, A30) or AMD MI200+
|
||||
- **VRAM**: Same as standard attention (Flash Attention doesn't increase memory)
|
||||
- **CUDA**: 12.0+ (11.8 minimum)
|
||||
- **PyTorch**: 2.2+ for native support
|
||||
|
||||
**Not supported**: V100 (Volta), CPU inference
|
||||
|
||||
## Resources
|
||||
|
||||
- Paper: "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness" (NeurIPS 2022)
|
||||
- Paper: "FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning" (ICLR 2024)
|
||||
- Blog: https://tridao.me/blog/2024/flash3/
|
||||
- GitHub: https://github.com/Dao-AILab/flash-attention
|
||||
- PyTorch docs: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html
|
||||
@@ -0,0 +1,595 @@
|
||||
---
|
||||
title: "Guidance — Constrain LLM output with grammars; guarantee valid JSON"
|
||||
sidebar_label: "Guidance"
|
||||
description: "Constrain LLM output with grammars; guarantee valid JSON"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Guidance
|
||||
|
||||
Constrain LLM output with grammars; guarantee valid JSON.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/guidance` |
|
||||
| Path | `optional-skills/mlops\guidance` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `guidance`, `transformers` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Prompt Engineering`, `Guidance`, `Constrained Generation`, `Structured Output`, `JSON Validation`, `Grammar`, `Microsoft Research`, `Format Enforcement`, `Multi-Step Workflows` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Guidance: Constrained LLM Generation
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use Guidance when you need to:
|
||||
- **Control LLM output syntax** with regex or grammars
|
||||
- **Guarantee valid JSON/XML/code** generation
|
||||
- **Reduce latency** vs traditional prompting approaches
|
||||
- **Enforce structured formats** (dates, emails, IDs, etc.)
|
||||
- **Build multi-step workflows** with Pythonic control flow
|
||||
- **Prevent invalid outputs** through grammatical constraints
|
||||
|
||||
**GitHub Stars**: 18,000+ | **From**: Microsoft Research
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Base installation
|
||||
pip install guidance
|
||||
|
||||
# With specific backends
|
||||
pip install guidance[transformers] # Hugging Face models
|
||||
pip install guidance[llama_cpp] # llama.cpp models
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Basic Example: Structured Generation
|
||||
|
||||
```python
|
||||
from guidance import models, gen
|
||||
|
||||
# Load model (supports OpenAI, Transformers, llama.cpp)
|
||||
lm = models.OpenAI("gpt-4")
|
||||
|
||||
# Generate with constraints
|
||||
result = lm + "The capital of France is " + gen("capital", max_tokens=5)
|
||||
|
||||
print(result["capital"]) # "Paris"
|
||||
```
|
||||
|
||||
### Chat format with a local model
|
||||
|
||||
> **Constraint support requires local logit access.** Regex, `select()`, and
|
||||
> grammar-based constrained generation only work with local backends
|
||||
> (`Transformers`, `LlamaCpp`). Remote API backends (`OpenAI`, and Azure
|
||||
> variants) support unconstrained `gen()` / chat only — they cannot enforce
|
||||
> token-level constraints. guidance 0.3.x has no `models.Anthropic` class.
|
||||
|
||||
```python
|
||||
from guidance import models, gen, system, user, assistant
|
||||
|
||||
# Local model (supports constrained generation)
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
|
||||
# Use context managers for chat format
|
||||
with system():
|
||||
lm += "You are a helpful assistant."
|
||||
|
||||
with user():
|
||||
lm += "What is the capital of France?"
|
||||
|
||||
with assistant():
|
||||
lm += gen(max_tokens=20)
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### 1. Context Managers
|
||||
|
||||
Guidance uses Pythonic context managers for chat-style interactions.
|
||||
|
||||
```python
|
||||
from guidance import system, user, assistant, gen
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
|
||||
# System message
|
||||
with system():
|
||||
lm += "You are a JSON generation expert."
|
||||
|
||||
# User message
|
||||
with user():
|
||||
lm += "Generate a person object with name and age."
|
||||
|
||||
# Assistant response
|
||||
with assistant():
|
||||
lm += gen("response", max_tokens=100)
|
||||
|
||||
print(lm["response"])
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- Natural chat flow
|
||||
- Clear role separation
|
||||
- Easy to read and maintain
|
||||
|
||||
### 2. Constrained Generation
|
||||
|
||||
Guidance ensures outputs match specified patterns using regex or grammars.
|
||||
|
||||
#### Regex Constraints
|
||||
|
||||
```python
|
||||
from guidance import models, gen
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
|
||||
# Constrain to valid email format
|
||||
lm += "Email: " + gen("email", regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
|
||||
|
||||
# Constrain to date format (YYYY-MM-DD)
|
||||
lm += "Date: " + gen("date", regex=r"\d{4}-\d{2}-\d{2}")
|
||||
|
||||
# Constrain to phone number
|
||||
lm += "Phone: " + gen("phone", regex=r"\d{3}-\d{3}-\d{4}")
|
||||
|
||||
print(lm["email"]) # Guaranteed valid email
|
||||
print(lm["date"]) # Guaranteed YYYY-MM-DD format
|
||||
```
|
||||
|
||||
**How it works:**
|
||||
- Regex converted to grammar at token level
|
||||
- Invalid tokens filtered during generation
|
||||
- Model can only produce matching outputs
|
||||
|
||||
#### Selection Constraints
|
||||
|
||||
```python
|
||||
from guidance import models, gen, select
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
|
||||
# Constrain to specific choices
|
||||
lm += "Sentiment: " + select(["positive", "negative", "neutral"], name="sentiment")
|
||||
|
||||
# Multiple-choice selection
|
||||
lm += "Best answer: " + select(
|
||||
["A) Paris", "B) London", "C) Berlin", "D) Madrid"],
|
||||
name="answer"
|
||||
)
|
||||
|
||||
print(lm["sentiment"]) # One of: positive, negative, neutral
|
||||
print(lm["answer"]) # One of: A, B, C, or D
|
||||
```
|
||||
|
||||
### 3. Token Healing
|
||||
|
||||
Guidance automatically "heals" token boundaries between prompt and generation.
|
||||
|
||||
**Problem:** Tokenization creates unnatural boundaries.
|
||||
|
||||
```python
|
||||
# Without token healing
|
||||
prompt = "The capital of France is "
|
||||
# Last token: " is "
|
||||
# First generated token might be " Par" (with leading space)
|
||||
# Result: "The capital of France is Paris" (double space!)
|
||||
```
|
||||
|
||||
**Solution:** Guidance backs up one token and regenerates.
|
||||
|
||||
```python
|
||||
from guidance import models, gen
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
|
||||
# Token healing enabled by default
|
||||
lm += "The capital of France is " + gen("capital", max_tokens=5)
|
||||
# Result: "The capital of France is Paris" (correct spacing)
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- Natural text boundaries
|
||||
- No awkward spacing issues
|
||||
- Better model performance (sees natural token sequences)
|
||||
|
||||
### 4. Grammar-Based Generation
|
||||
|
||||
Define complex structures by composing grammar functions. The template-string
|
||||
`grammar=` form is not part of current guidance — build grammars from
|
||||
composable functions, or use `guidance.json()` for JSON.
|
||||
|
||||
```python
|
||||
from guidance import models, gen
|
||||
from guidance import json as gen_json
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
|
||||
# JSON via a Pydantic schema (guidance.json compiles the schema to a grammar)
|
||||
class Person(BaseModel):
|
||||
name: str = Field(pattern=r"[A-Za-z ]+")
|
||||
age: int
|
||||
email: str = Field(pattern=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
|
||||
|
||||
lm += gen_json(name="person", schema=Person)
|
||||
|
||||
print(lm["person"]) # Guaranteed valid JSON matching the schema
|
||||
|
||||
# Or compose grammar functions directly:
|
||||
grammar = "name=" + gen("name", regex=r"[A-Za-z ]+") + " age=" + gen("age", regex=r"[0-9]+")
|
||||
lm += grammar
|
||||
```
|
||||
|
||||
**Use cases:**
|
||||
- Complex structured outputs
|
||||
- Nested data structures
|
||||
- Programming language syntax
|
||||
- Domain-specific languages
|
||||
|
||||
### 5. Guidance Functions
|
||||
|
||||
Create reusable generation patterns with the `@guidance` decorator.
|
||||
|
||||
```python
|
||||
from guidance import guidance, gen, models
|
||||
|
||||
@guidance
|
||||
def generate_person(lm):
|
||||
"""Generate a person with name and age."""
|
||||
lm += "Name: " + gen("name", max_tokens=20, stop="\n")
|
||||
lm += "\nAge: " + gen("age", regex=r"[0-9]+", max_tokens=3)
|
||||
return lm
|
||||
|
||||
# Use the function
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
lm = generate_person(lm)
|
||||
|
||||
print(lm["name"])
|
||||
print(lm["age"])
|
||||
```
|
||||
|
||||
**Stateful Functions:**
|
||||
|
||||
```python
|
||||
@guidance(stateless=False)
|
||||
def react_agent(lm, question, tools, max_rounds=5):
|
||||
"""ReAct agent with tool use."""
|
||||
lm += f"Question: {question}\n\n"
|
||||
|
||||
for i in range(max_rounds):
|
||||
# Thought
|
||||
lm += f"Thought {i+1}: " + gen("thought", stop="\n")
|
||||
|
||||
# Action
|
||||
lm += "\nAction: " + select(list(tools.keys()), name="action")
|
||||
|
||||
# Execute tool
|
||||
tool_result = tools[lm["action"]]()
|
||||
lm += f"\nObservation: {tool_result}\n\n"
|
||||
|
||||
# Check if done
|
||||
lm += "Done? " + select(["Yes", "No"], name="done")
|
||||
if lm["done"] == "Yes":
|
||||
break
|
||||
|
||||
# Final answer
|
||||
lm += "\nFinal Answer: " + gen("answer", max_tokens=100)
|
||||
return lm
|
||||
```
|
||||
|
||||
## Backend Configuration
|
||||
|
||||
### OpenAI (remote — unconstrained only)
|
||||
|
||||
> Remote API backends cannot do constrained generation (regex/select/grammar);
|
||||
> use them only for plain chat/`gen()`. For constraints, use a local backend.
|
||||
|
||||
```python
|
||||
from guidance import models
|
||||
|
||||
lm = models.OpenAI(
|
||||
model="gpt-4o-mini",
|
||||
api_key="your-api-key" # Or set OPENAI_API_KEY env var
|
||||
)
|
||||
```
|
||||
|
||||
### Local Models (Transformers)
|
||||
|
||||
```python
|
||||
from guidance.models import Transformers
|
||||
|
||||
lm = Transformers(
|
||||
"microsoft/Phi-4-mini-instruct",
|
||||
device="cuda" # Or "cpu"
|
||||
)
|
||||
```
|
||||
|
||||
### Local Models (llama.cpp)
|
||||
|
||||
```python
|
||||
from guidance.models import LlamaCpp
|
||||
|
||||
lm = LlamaCpp(
|
||||
model_path="/path/to/model.gguf",
|
||||
n_ctx=4096,
|
||||
n_gpu_layers=35
|
||||
)
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Pattern 1: JSON Generation
|
||||
|
||||
```python
|
||||
from guidance import models, gen, system, user, assistant
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
|
||||
with system():
|
||||
lm += "You generate valid JSON."
|
||||
|
||||
with user():
|
||||
lm += "Generate a user profile with name, age, and email."
|
||||
|
||||
with assistant():
|
||||
lm += """{
|
||||
"name": """ + gen("name", regex=r'"[A-Za-z ]+"', max_tokens=30) + """,
|
||||
"age": """ + gen("age", regex=r"[0-9]+", max_tokens=3) + """,
|
||||
"email": """ + gen("email", regex=r'"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"', max_tokens=50) + """
|
||||
}"""
|
||||
|
||||
print(lm) # Valid JSON guaranteed
|
||||
```
|
||||
|
||||
### Pattern 2: Classification
|
||||
|
||||
```python
|
||||
from guidance import models, gen, select
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
|
||||
text = "This product is amazing! I love it."
|
||||
|
||||
lm += f"Text: {text}\n"
|
||||
lm += "Sentiment: " + select(["positive", "negative", "neutral"], name="sentiment")
|
||||
lm += "\nConfidence: " + gen("confidence", regex=r"[0-9]+", max_tokens=3) + "%"
|
||||
|
||||
print(f"Sentiment: {lm['sentiment']}")
|
||||
print(f"Confidence: {lm['confidence']}%")
|
||||
```
|
||||
|
||||
### Pattern 3: Multi-Step Reasoning
|
||||
|
||||
```python
|
||||
from guidance import models, gen, guidance
|
||||
|
||||
@guidance
|
||||
def chain_of_thought(lm, question):
|
||||
"""Generate answer with step-by-step reasoning."""
|
||||
lm += f"Question: {question}\n\n"
|
||||
|
||||
# Generate multiple reasoning steps
|
||||
for i in range(3):
|
||||
lm += f"Step {i+1}: " + gen(f"step_{i+1}", stop="\n", max_tokens=100) + "\n"
|
||||
|
||||
# Final answer
|
||||
lm += "\nTherefore, the answer is: " + gen("answer", max_tokens=50)
|
||||
|
||||
return lm
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
lm = chain_of_thought(lm, "What is 15% of 200?")
|
||||
|
||||
print(lm["answer"])
|
||||
```
|
||||
|
||||
### Pattern 4: ReAct Agent
|
||||
|
||||
```python
|
||||
from guidance import models, gen, select, guidance
|
||||
|
||||
@guidance(stateless=False)
|
||||
def react_agent(lm, question):
|
||||
"""ReAct agent with tool use."""
|
||||
tools = {
|
||||
"calculator": lambda expr: eval(expr),
|
||||
"search": lambda query: f"Search results for: {query}",
|
||||
}
|
||||
|
||||
lm += f"Question: {question}\n\n"
|
||||
|
||||
for round in range(5):
|
||||
# Thought
|
||||
lm += f"Thought: " + gen("thought", stop="\n") + "\n"
|
||||
|
||||
# Action selection
|
||||
lm += "Action: " + select(["calculator", "search", "answer"], name="action")
|
||||
|
||||
if lm["action"] == "answer":
|
||||
lm += "\nFinal Answer: " + gen("answer", max_tokens=100)
|
||||
break
|
||||
|
||||
# Action input
|
||||
lm += "\nAction Input: " + gen("action_input", stop="\n") + "\n"
|
||||
|
||||
# Execute tool
|
||||
if lm["action"] in tools:
|
||||
result = tools[lm["action"]](lm["action_input"])
|
||||
lm += f"Observation: {result}\n\n"
|
||||
|
||||
return lm
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
lm = react_agent(lm, "What is 25 * 4 + 10?")
|
||||
print(lm["answer"])
|
||||
```
|
||||
|
||||
### Pattern 5: Data Extraction
|
||||
|
||||
```python
|
||||
from guidance import models, gen, guidance
|
||||
|
||||
@guidance
|
||||
def extract_entities(lm, text):
|
||||
"""Extract structured entities from text."""
|
||||
lm += f"Text: {text}\n\n"
|
||||
|
||||
# Extract person
|
||||
lm += "Person: " + gen("person", stop="\n", max_tokens=30) + "\n"
|
||||
|
||||
# Extract organization
|
||||
lm += "Organization: " + gen("organization", stop="\n", max_tokens=30) + "\n"
|
||||
|
||||
# Extract date
|
||||
lm += "Date: " + gen("date", regex=r"\d{4}-\d{2}-\d{2}", max_tokens=10) + "\n"
|
||||
|
||||
# Extract location
|
||||
lm += "Location: " + gen("location", stop="\n", max_tokens=30) + "\n"
|
||||
|
||||
return lm
|
||||
|
||||
text = "Tim Cook announced at Apple Park on 2024-09-15 in Cupertino."
|
||||
|
||||
lm = models.Transformers("microsoft/Phi-4-mini-instruct")
|
||||
lm = extract_entities(lm, text)
|
||||
|
||||
print(f"Person: {lm['person']}")
|
||||
print(f"Organization: {lm['organization']}")
|
||||
print(f"Date: {lm['date']}")
|
||||
print(f"Location: {lm['location']}")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Use Regex for Format Validation
|
||||
|
||||
```python
|
||||
# ✅ Good: Regex ensures valid format
|
||||
lm += "Email: " + gen("email", regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
|
||||
|
||||
# ❌ Bad: Free generation may produce invalid emails
|
||||
lm += "Email: " + gen("email", max_tokens=50)
|
||||
```
|
||||
|
||||
### 2. Use select() for Fixed Categories
|
||||
|
||||
```python
|
||||
# ✅ Good: Guaranteed valid category
|
||||
lm += "Status: " + select(["pending", "approved", "rejected"], name="status")
|
||||
|
||||
# ❌ Bad: May generate typos or invalid values
|
||||
lm += "Status: " + gen("status", max_tokens=20)
|
||||
```
|
||||
|
||||
### 3. Leverage Token Healing
|
||||
|
||||
```python
|
||||
# Token healing is enabled by default
|
||||
# No special action needed - just concatenate naturally
|
||||
lm += "The capital is " + gen("capital") # Automatic healing
|
||||
```
|
||||
|
||||
### 4. Use stop Sequences
|
||||
|
||||
```python
|
||||
# ✅ Good: Stop at newline for single-line outputs
|
||||
lm += "Name: " + gen("name", stop="\n")
|
||||
|
||||
# ❌ Bad: May generate multiple lines
|
||||
lm += "Name: " + gen("name", max_tokens=50)
|
||||
```
|
||||
|
||||
### 5. Create Reusable Functions
|
||||
|
||||
```python
|
||||
# ✅ Good: Reusable pattern
|
||||
@guidance
|
||||
def generate_person(lm):
|
||||
lm += "Name: " + gen("name", stop="\n")
|
||||
lm += "\nAge: " + gen("age", regex=r"[0-9]+")
|
||||
return lm
|
||||
|
||||
# Use multiple times
|
||||
lm = generate_person(lm)
|
||||
lm += "\n\n"
|
||||
lm = generate_person(lm)
|
||||
```
|
||||
|
||||
### 6. Balance Constraints
|
||||
|
||||
```python
|
||||
# ✅ Good: Reasonable constraints
|
||||
lm += gen("name", regex=r"[A-Za-z ]+", max_tokens=30)
|
||||
|
||||
# ❌ Too strict: May fail or be very slow
|
||||
lm += gen("name", regex=r"^(John|Jane)$", max_tokens=10)
|
||||
```
|
||||
|
||||
## Comparison to Alternatives
|
||||
|
||||
| Feature | Guidance | Instructor | Outlines | LMQL |
|
||||
|---------|----------|------------|----------|------|
|
||||
| Regex Constraints | ✅ Yes | ❌ No | ✅ Yes | ✅ Yes |
|
||||
| Grammar Support | ✅ CFG | ❌ No | ✅ CFG | ✅ CFG |
|
||||
| Pydantic Validation | ❌ No | ✅ Yes | ✅ Yes | ❌ No |
|
||||
| Token Healing | ✅ Yes | ❌ No | ✅ Yes | ❌ No |
|
||||
| Local Models | ✅ Yes | ⚠️ Limited | ✅ Yes | ✅ Yes |
|
||||
| API Models | ✅ Yes | ✅ Yes | ⚠️ Limited | ✅ Yes |
|
||||
| Pythonic Syntax | ✅ Yes | ✅ Yes | ✅ Yes | ❌ SQL-like |
|
||||
| Learning Curve | Low | Low | Medium | High |
|
||||
|
||||
**When to choose Guidance:**
|
||||
- Need regex/grammar constraints
|
||||
- Want token healing
|
||||
- Building complex workflows with control flow
|
||||
- Using local models (Transformers, llama.cpp)
|
||||
- Prefer Pythonic syntax
|
||||
|
||||
**When to choose alternatives:**
|
||||
- Instructor: Need Pydantic validation with automatic retrying
|
||||
- Outlines: Need JSON schema validation
|
||||
- LMQL: Prefer declarative query syntax
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
**Latency Reduction:**
|
||||
- 30-50% faster than traditional prompting for constrained outputs
|
||||
- Token healing reduces unnecessary regeneration
|
||||
- Grammar constraints prevent invalid token generation
|
||||
|
||||
**Memory Usage:**
|
||||
- Minimal overhead vs unconstrained generation
|
||||
- Grammar compilation cached after first use
|
||||
- Efficient token filtering at inference time
|
||||
|
||||
**Token Efficiency:**
|
||||
- Prevents wasted tokens on invalid outputs
|
||||
- No need for retry loops
|
||||
- Direct path to valid outputs
|
||||
|
||||
## Resources
|
||||
|
||||
- **Documentation**: https://guidance.readthedocs.io
|
||||
- **GitHub**: https://github.com/guidance-ai/guidance (18k+ stars)
|
||||
- **Notebooks**: https://github.com/guidance-ai/guidance/tree/main/notebooks
|
||||
- **Discord**: Community support available
|
||||
|
||||
## See Also
|
||||
|
||||
- `references/constraints.md` - Comprehensive regex and grammar patterns
|
||||
- `references/backends.md` - Backend-specific configuration
|
||||
- `references/examples.md` - Production-ready examples
|
||||
@@ -0,0 +1,535 @@
|
||||
---
|
||||
title: "Huggingface Tokenizers — Fast BPE/WordPiece tokenization and custom vocab training"
|
||||
sidebar_label: "Huggingface Tokenizers"
|
||||
description: "Fast BPE/WordPiece tokenization and custom vocab training"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Huggingface Tokenizers
|
||||
|
||||
Fast BPE/WordPiece tokenization and custom vocab training.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/huggingface-tokenizers` |
|
||||
| Path | `optional-skills/mlops\huggingface-tokenizers` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `tokenizers`, `transformers`, `datasets` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Tokenization`, `HuggingFace`, `BPE`, `WordPiece`, `Unigram`, `Fast Tokenization`, `Rust`, `Custom Tokenizer`, `Alignment Tracking`, `Production` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# HuggingFace Tokenizers - Fast Tokenization for NLP
|
||||
|
||||
Fast, production-ready tokenizers with Rust performance and Python ease-of-use.
|
||||
|
||||
## When to use HuggingFace Tokenizers
|
||||
|
||||
**Use HuggingFace Tokenizers when:**
|
||||
- Need extremely fast tokenization (<20s per GB of text)
|
||||
- Training custom tokenizers from scratch
|
||||
- Want alignment tracking (token → original text position)
|
||||
- Building production NLP pipelines
|
||||
- Need to tokenize large corpora efficiently
|
||||
|
||||
**Performance**:
|
||||
- **Speed**: <20 seconds to tokenize 1GB on CPU
|
||||
- **Implementation**: Rust core with Python/Node.js bindings
|
||||
- **Efficiency**: 10-100× faster than pure Python implementations
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **SentencePiece**: Language-independent, used by T5/ALBERT
|
||||
- **tiktoken**: OpenAI's BPE tokenizer for GPT models
|
||||
- **transformers AutoTokenizer**: Loading pretrained only (uses this library internally)
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Install tokenizers
|
||||
pip install tokenizers
|
||||
|
||||
# With transformers integration
|
||||
pip install tokenizers transformers
|
||||
```
|
||||
|
||||
### Load pretrained tokenizer
|
||||
|
||||
```python
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
# Load from HuggingFace Hub
|
||||
tokenizer = Tokenizer.from_pretrained("bert-base-uncased")
|
||||
|
||||
# Encode text
|
||||
output = tokenizer.encode("Hello, how are you?")
|
||||
print(output.tokens) # ['hello', ',', 'how', 'are', 'you', '?']
|
||||
print(output.ids) # [7592, 1010, 2129, 2024, 2017, 1029]
|
||||
|
||||
# Decode back
|
||||
text = tokenizer.decode(output.ids)
|
||||
print(text) # "hello, how are you?"
|
||||
```
|
||||
|
||||
### Train custom BPE tokenizer
|
||||
|
||||
```python
|
||||
from tokenizers import Tokenizer
|
||||
from tokenizers.models import BPE
|
||||
from tokenizers.trainers import BpeTrainer
|
||||
from tokenizers.pre_tokenizers import Whitespace
|
||||
|
||||
# Initialize tokenizer with BPE model
|
||||
tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
|
||||
tokenizer.pre_tokenizer = Whitespace()
|
||||
|
||||
# Configure trainer
|
||||
trainer = BpeTrainer(
|
||||
vocab_size=30000,
|
||||
special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"],
|
||||
min_frequency=2
|
||||
)
|
||||
|
||||
# Train on files
|
||||
files = ["train.txt", "validation.txt"]
|
||||
tokenizer.train(files, trainer)
|
||||
|
||||
# Save
|
||||
tokenizer.save("my-tokenizer.json")
|
||||
```
|
||||
|
||||
**Training time**: ~1-2 minutes for 100MB corpus, ~10-20 minutes for 1GB
|
||||
|
||||
### Batch encoding with padding
|
||||
|
||||
```python
|
||||
# Enable padding
|
||||
tokenizer.enable_padding(pad_id=3, pad_token="[PAD]")
|
||||
|
||||
# Encode batch
|
||||
texts = ["Hello world", "This is a longer sentence"]
|
||||
encodings = tokenizer.encode_batch(texts)
|
||||
|
||||
for encoding in encodings:
|
||||
print(encoding.ids)
|
||||
# [101, 7592, 2088, 102, 3, 3, 3]
|
||||
# [101, 2023, 2003, 1037, 2936, 6251, 102]
|
||||
```
|
||||
|
||||
## Tokenization algorithms
|
||||
|
||||
### BPE (Byte-Pair Encoding)
|
||||
|
||||
**How it works**:
|
||||
1. Start with character-level vocabulary
|
||||
2. Find most frequent character pair
|
||||
3. Merge into new token, add to vocabulary
|
||||
4. Repeat until vocabulary size reached
|
||||
|
||||
**Used by**: GPT-2, GPT-3, RoBERTa, BART, DeBERTa
|
||||
|
||||
```python
|
||||
from tokenizers import Tokenizer
|
||||
from tokenizers.models import BPE
|
||||
from tokenizers.trainers import BpeTrainer
|
||||
from tokenizers.pre_tokenizers import ByteLevel
|
||||
|
||||
tokenizer = Tokenizer(BPE(unk_token="<|endoftext|>"))
|
||||
tokenizer.pre_tokenizer = ByteLevel()
|
||||
|
||||
trainer = BpeTrainer(
|
||||
vocab_size=50257,
|
||||
special_tokens=["<|endoftext|>"],
|
||||
min_frequency=2
|
||||
)
|
||||
|
||||
tokenizer.train(files=["data.txt"], trainer=trainer)
|
||||
```
|
||||
|
||||
**Advantages**:
|
||||
- Handles OOV words well (breaks into subwords)
|
||||
- Flexible vocabulary size
|
||||
- Good for morphologically rich languages
|
||||
|
||||
**Trade-offs**:
|
||||
- Tokenization depends on merge order
|
||||
- May split common words unexpectedly
|
||||
|
||||
### WordPiece
|
||||
|
||||
**How it works**:
|
||||
1. Start with character vocabulary
|
||||
2. Score merge pairs: `frequency(pair) / (frequency(first) × frequency(second))`
|
||||
3. Merge highest scoring pair
|
||||
4. Repeat until vocabulary size reached
|
||||
|
||||
**Used by**: BERT, DistilBERT, MobileBERT
|
||||
|
||||
```python
|
||||
from tokenizers import Tokenizer
|
||||
from tokenizers.models import WordPiece
|
||||
from tokenizers.trainers import WordPieceTrainer
|
||||
from tokenizers.pre_tokenizers import Whitespace
|
||||
from tokenizers.normalizers import BertNormalizer
|
||||
|
||||
tokenizer = Tokenizer(WordPiece(unk_token="[UNK]"))
|
||||
tokenizer.normalizer = BertNormalizer(lowercase=True)
|
||||
tokenizer.pre_tokenizer = Whitespace()
|
||||
|
||||
trainer = WordPieceTrainer(
|
||||
vocab_size=30522,
|
||||
special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"],
|
||||
continuing_subword_prefix="##"
|
||||
)
|
||||
|
||||
tokenizer.train(files=["corpus.txt"], trainer=trainer)
|
||||
```
|
||||
|
||||
**Advantages**:
|
||||
- Prioritizes meaningful merges (high score = semantically related)
|
||||
- Used successfully in BERT (state-of-the-art results)
|
||||
|
||||
**Trade-offs**:
|
||||
- Unknown words become `[UNK]` if no subword match
|
||||
- Saves vocabulary, not merge rules (larger files)
|
||||
|
||||
### Unigram
|
||||
|
||||
**How it works**:
|
||||
1. Start with large vocabulary (all substrings)
|
||||
2. Compute loss for corpus with current vocabulary
|
||||
3. Remove tokens with minimal impact on loss
|
||||
4. Repeat until vocabulary size reached
|
||||
|
||||
**Used by**: ALBERT, T5, mBART, XLNet (via SentencePiece)
|
||||
|
||||
```python
|
||||
from tokenizers import Tokenizer
|
||||
from tokenizers.models import Unigram
|
||||
from tokenizers.trainers import UnigramTrainer
|
||||
|
||||
tokenizer = Tokenizer(Unigram())
|
||||
|
||||
trainer = UnigramTrainer(
|
||||
vocab_size=8000,
|
||||
special_tokens=["<unk>", "<s>", "</s>"],
|
||||
unk_token="<unk>"
|
||||
)
|
||||
|
||||
tokenizer.train(files=["data.txt"], trainer=trainer)
|
||||
```
|
||||
|
||||
**Advantages**:
|
||||
- Probabilistic (finds most likely tokenization)
|
||||
- Works well for languages without word boundaries
|
||||
- Handles diverse linguistic contexts
|
||||
|
||||
**Trade-offs**:
|
||||
- Computationally expensive to train
|
||||
- More hyperparameters to tune
|
||||
|
||||
## Tokenization pipeline
|
||||
|
||||
Complete pipeline: **Normalization → Pre-tokenization → Model → Post-processing**
|
||||
|
||||
### Normalization
|
||||
|
||||
Clean and standardize text:
|
||||
|
||||
```python
|
||||
from tokenizers.normalizers import NFD, StripAccents, Lowercase, Sequence
|
||||
|
||||
tokenizer.normalizer = Sequence([
|
||||
NFD(), # Unicode normalization (decompose)
|
||||
Lowercase(), # Convert to lowercase
|
||||
StripAccents() # Remove accents
|
||||
])
|
||||
|
||||
# Input: "Héllo WORLD"
|
||||
# After normalization: "hello world"
|
||||
```
|
||||
|
||||
**Common normalizers**:
|
||||
- `NFD`, `NFC`, `NFKD`, `NFKC` - Unicode normalization forms
|
||||
- `Lowercase()` - Convert to lowercase
|
||||
- `StripAccents()` - Remove accents (é → e)
|
||||
- `Strip()` - Remove whitespace
|
||||
- `Replace(pattern, content)` - Regex replacement
|
||||
|
||||
### Pre-tokenization
|
||||
|
||||
Split text into word-like units:
|
||||
|
||||
```python
|
||||
from tokenizers.pre_tokenizers import Whitespace, Punctuation, Sequence, ByteLevel
|
||||
|
||||
# Split on whitespace and punctuation
|
||||
tokenizer.pre_tokenizer = Sequence([
|
||||
Whitespace(),
|
||||
Punctuation()
|
||||
])
|
||||
|
||||
# Input: "Hello, world!"
|
||||
# After pre-tokenization: ["Hello", ",", "world", "!"]
|
||||
```
|
||||
|
||||
**Common pre-tokenizers**:
|
||||
- `Whitespace()` - Split on spaces, tabs, newlines
|
||||
- `ByteLevel()` - GPT-2 style byte-level splitting
|
||||
- `Punctuation()` - Isolate punctuation
|
||||
- `Digits(individual_digits=True)` - Split digits individually
|
||||
- `Metaspace()` - Replace spaces with ▁ (SentencePiece style)
|
||||
|
||||
### Post-processing
|
||||
|
||||
Add special tokens for model input:
|
||||
|
||||
```python
|
||||
from tokenizers.processors import TemplateProcessing
|
||||
|
||||
# BERT-style: [CLS] sentence [SEP]
|
||||
tokenizer.post_processor = TemplateProcessing(
|
||||
single="[CLS] $A [SEP]",
|
||||
pair="[CLS] $A [SEP] $B [SEP]",
|
||||
special_tokens=[
|
||||
("[CLS]", 1),
|
||||
("[SEP]", 2),
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
**Common patterns**:
|
||||
```python
|
||||
# GPT-2: sentence <|endoftext|>
|
||||
TemplateProcessing(
|
||||
single="$A <|endoftext|>",
|
||||
special_tokens=[("<|endoftext|>", 50256)]
|
||||
)
|
||||
|
||||
# RoBERTa: <s> sentence </s>
|
||||
TemplateProcessing(
|
||||
single="<s> $A </s>",
|
||||
pair="<s> $A </s> </s> $B </s>",
|
||||
special_tokens=[("<s>", 0), ("</s>", 2)]
|
||||
)
|
||||
```
|
||||
|
||||
## Alignment tracking
|
||||
|
||||
Track token positions in original text:
|
||||
|
||||
```python
|
||||
output = tokenizer.encode("Hello, world!")
|
||||
|
||||
# Get token offsets
|
||||
for token, offset in zip(output.tokens, output.offsets):
|
||||
start, end = offset
|
||||
print(f"{token:10} → [{start:2}, {end:2}): {text[start:end]!r}")
|
||||
|
||||
# Output:
|
||||
# hello → [ 0, 5): 'Hello'
|
||||
# , → [ 5, 6): ','
|
||||
# world → [ 7, 12): 'world'
|
||||
# ! → [12, 13): '!'
|
||||
```
|
||||
|
||||
**Use cases**:
|
||||
- Named entity recognition (map predictions back to text)
|
||||
- Question answering (extract answer spans)
|
||||
- Token classification (align labels to original positions)
|
||||
|
||||
## Integration with transformers
|
||||
|
||||
### Load with AutoTokenizer
|
||||
|
||||
```python
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
# AutoTokenizer automatically uses fast tokenizers
|
||||
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
|
||||
|
||||
# Check if using fast tokenizer
|
||||
print(tokenizer.is_fast) # True
|
||||
|
||||
# Access underlying tokenizers.Tokenizer
|
||||
fast_tokenizer = tokenizer.backend_tokenizer
|
||||
print(type(fast_tokenizer)) # <class 'tokenizers.Tokenizer'>
|
||||
```
|
||||
|
||||
### Convert custom tokenizer to transformers
|
||||
|
||||
```python
|
||||
from tokenizers import Tokenizer
|
||||
from transformers import PreTrainedTokenizerFast
|
||||
|
||||
# Train custom tokenizer
|
||||
tokenizer = Tokenizer(BPE())
|
||||
# ... train tokenizer ...
|
||||
tokenizer.save("my-tokenizer.json")
|
||||
|
||||
# Wrap for transformers
|
||||
transformers_tokenizer = PreTrainedTokenizerFast(
|
||||
tokenizer_file="my-tokenizer.json",
|
||||
unk_token="[UNK]",
|
||||
pad_token="[PAD]",
|
||||
cls_token="[CLS]",
|
||||
sep_token="[SEP]",
|
||||
mask_token="[MASK]"
|
||||
)
|
||||
|
||||
# Use like any transformers tokenizer
|
||||
outputs = transformers_tokenizer(
|
||||
"Hello world",
|
||||
padding=True,
|
||||
truncation=True,
|
||||
max_length=512,
|
||||
return_tensors="pt"
|
||||
)
|
||||
```
|
||||
|
||||
## Common patterns
|
||||
|
||||
### Train from iterator (large datasets)
|
||||
|
||||
```python
|
||||
from datasets import load_dataset
|
||||
|
||||
# Load dataset
|
||||
dataset = load_dataset("wikitext", "wikitext-103-raw-v1", split="train")
|
||||
|
||||
# Create batch iterator
|
||||
def batch_iterator(batch_size=1000):
|
||||
for i in range(0, len(dataset), batch_size):
|
||||
yield dataset[i:i + batch_size]["text"]
|
||||
|
||||
# Train tokenizer
|
||||
tokenizer.train_from_iterator(
|
||||
batch_iterator(),
|
||||
trainer=trainer,
|
||||
length=len(dataset) # For progress bar
|
||||
)
|
||||
```
|
||||
|
||||
**Performance**: Processes 1GB in ~10-20 minutes
|
||||
|
||||
### Enable truncation and padding
|
||||
|
||||
```python
|
||||
# Enable truncation
|
||||
tokenizer.enable_truncation(max_length=512)
|
||||
|
||||
# Enable padding
|
||||
tokenizer.enable_padding(
|
||||
pad_id=tokenizer.token_to_id("[PAD]"),
|
||||
pad_token="[PAD]",
|
||||
length=512 # Fixed length, or None for batch max
|
||||
)
|
||||
|
||||
# Encode with both
|
||||
output = tokenizer.encode("This is a long sentence that will be truncated...")
|
||||
print(len(output.ids)) # 512
|
||||
```
|
||||
|
||||
### Multi-processing
|
||||
|
||||
```python
|
||||
from tokenizers import Tokenizer
|
||||
from multiprocessing import Pool
|
||||
|
||||
# Load tokenizer
|
||||
tokenizer = Tokenizer.from_file("tokenizer.json")
|
||||
|
||||
def encode_batch(texts):
|
||||
return tokenizer.encode_batch(texts)
|
||||
|
||||
# Process large corpus in parallel
|
||||
with Pool(8) as pool:
|
||||
# Split corpus into chunks
|
||||
chunk_size = 1000
|
||||
chunks = [corpus[i:i+chunk_size] for i in range(0, len(corpus), chunk_size)]
|
||||
|
||||
# Encode in parallel
|
||||
results = pool.map(encode_batch, chunks)
|
||||
```
|
||||
|
||||
**Speedup**: 5-8× with 8 cores
|
||||
|
||||
## Performance benchmarks
|
||||
|
||||
### Training speed
|
||||
|
||||
| Corpus Size | BPE (30k vocab) | WordPiece (30k) | Unigram (8k) |
|
||||
|-------------|-----------------|-----------------|--------------|
|
||||
| 10 MB | 15 sec | 18 sec | 25 sec |
|
||||
| 100 MB | 1.5 min | 2 min | 4 min |
|
||||
| 1 GB | 15 min | 20 min | 40 min |
|
||||
|
||||
**Hardware**: 16-core CPU, tested on English Wikipedia
|
||||
|
||||
### Tokenization speed
|
||||
|
||||
| Implementation | 1 GB corpus | Throughput |
|
||||
|----------------|-------------|---------------|
|
||||
| Pure Python | ~20 minutes | ~50 MB/min |
|
||||
| HF Tokenizers | ~15 seconds | ~4 GB/min |
|
||||
| **Speedup** | **80×** | **80×** |
|
||||
|
||||
**Test**: English text, average sentence length 20 words
|
||||
|
||||
### Memory usage
|
||||
|
||||
| Task | Memory |
|
||||
|-------------------------|---------|
|
||||
| Load tokenizer | ~10 MB |
|
||||
| Train BPE (30k vocab) | ~200 MB |
|
||||
| Encode 1M sentences | ~500 MB |
|
||||
|
||||
## Supported models
|
||||
|
||||
Pre-trained tokenizers available via `from_pretrained()`:
|
||||
|
||||
**BERT family**:
|
||||
- `bert-base-uncased`, `bert-large-cased`
|
||||
- `distilbert-base-uncased`
|
||||
- `roberta-base`, `roberta-large`
|
||||
|
||||
**GPT family**:
|
||||
- `gpt2`, `gpt2-medium`, `gpt2-large`
|
||||
- `distilgpt2`
|
||||
|
||||
**T5 family**:
|
||||
- `t5-small`, `t5-base`, `t5-large`
|
||||
- `google/flan-t5-xxl`
|
||||
|
||||
**Other**:
|
||||
- `facebook/bart-base`, `facebook/mbart-large-cc25`
|
||||
- `albert-base-v2`, `albert-xlarge-v2`
|
||||
- `xlm-roberta-base`, `xlm-roberta-large`
|
||||
|
||||
Browse all: https://huggingface.co/models?library=tokenizers
|
||||
|
||||
## References
|
||||
|
||||
- **[Training Guide](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\huggingface-tokenizers/references/training.md)** - Train custom tokenizers, configure trainers, handle large datasets
|
||||
- **[Algorithms Deep Dive](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\huggingface-tokenizers/references/algorithms.md)** - BPE, WordPiece, Unigram explained in detail
|
||||
- **[Pipeline Components](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\huggingface-tokenizers/references/pipeline.md)** - Normalizers, pre-tokenizers, post-processors, decoders
|
||||
- **[Transformers Integration](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\huggingface-tokenizers/references/integration.md)** - AutoTokenizer, PreTrainedTokenizerFast, special tokens
|
||||
|
||||
## Resources
|
||||
|
||||
- **Docs**: https://huggingface.co/docs/tokenizers
|
||||
- **GitHub**: https://github.com/huggingface/tokenizers ⭐ 9,000+
|
||||
- **Version**: 0.20.0+
|
||||
- **Course**: https://huggingface.co/learn/nlp-course/chapter6/1
|
||||
- **Paper**: BPE (Sennrich et al., 2016), WordPiece (Schuster & Nakajima, 2012)
|
||||
@@ -0,0 +1,267 @@
|
||||
---
|
||||
title: "Llama Cpp — llama.cpp local GGUF inference + HF Hub model discovery"
|
||||
sidebar_label: "Llama Cpp"
|
||||
description: "llama.cpp local GGUF inference + HF Hub model discovery"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Llama Cpp
|
||||
|
||||
llama.cpp local GGUF inference + HF Hub model discovery.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/llama-cpp` |
|
||||
| Path | `optional-skills/mlops\inference\llama-cpp` |
|
||||
| Version | `2.1.2` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `llama-cpp-python>=0.2.0` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `llama.cpp`, `GGUF`, `Quantization`, `Hugging Face Hub`, `CPU Inference`, `Apple Silicon`, `Edge Deployment`, `AMD GPUs`, `Intel GPUs`, `NVIDIA`, `URL-first` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# llama.cpp + GGUF
|
||||
|
||||
Use this skill for local GGUF inference, quant selection, or Hugging Face repo discovery for llama.cpp.
|
||||
|
||||
## When to use
|
||||
|
||||
- Run local models on CPU, Apple Silicon, CUDA, ROCm, or Intel GPUs
|
||||
- Find the right GGUF for a specific Hugging Face repo
|
||||
- Build a `llama-server` or `llama-cli` command from the Hub
|
||||
- Search the Hub for models that already support llama.cpp
|
||||
- Enumerate available `.gguf` files and sizes for a repo
|
||||
- Decide between Q4/Q5/Q6/IQ variants for the user's RAM or VRAM
|
||||
|
||||
## Model Discovery workflow
|
||||
|
||||
Prefer URL workflows before asking for `hf`, Python, or custom scripts.
|
||||
|
||||
1. Search for candidate repos on the Hub:
|
||||
- Base: `https://huggingface.co/models?apps=llama.cpp&sort=trending`
|
||||
- Add `search=<term>` for a model family
|
||||
- Add `num_parameters=min:0,max:24B` or similar when the user has size constraints
|
||||
2. Open the repo with the llama.cpp local-app view:
|
||||
- `https://huggingface.co/<repo>?local-app=llama.cpp`
|
||||
3. Treat the local-app snippet as the source of truth when it is visible:
|
||||
- copy the exact `llama-server` or `llama-cli` command
|
||||
- report the recommended quant exactly as HF shows it
|
||||
4. Read the same `?local-app=llama.cpp` URL as page text or HTML and extract the section under `Hardware compatibility`:
|
||||
- prefer its exact quant labels and sizes over generic tables
|
||||
- keep repo-specific labels such as `UD-Q4_K_M` or `IQ4_NL_XL`
|
||||
- if that section is not visible in the fetched page source, say so and fall back to the tree API plus generic quant guidance
|
||||
5. Query the tree API to confirm what actually exists:
|
||||
- `https://huggingface.co/api/models/<repo>/tree/main?recursive=true`
|
||||
- keep entries where `type` is `file` and `path` ends with `.gguf`
|
||||
- use `path` and `size` as the source of truth for filenames and byte sizes
|
||||
- separate quantized checkpoints from `mmproj-*.gguf` projector files and `BF16/` shard files
|
||||
- use `https://huggingface.co/<repo>/tree/main` only as a human fallback
|
||||
6. If the local-app snippet is not text-visible, reconstruct the command from the repo plus the chosen quant:
|
||||
- shorthand quant selection: `llama-server -hf <repo>:<QUANT>`
|
||||
- exact-file fallback: `llama-server --hf-repo <repo> --hf-file <filename.gguf>`
|
||||
7. Only suggest conversion from Transformers weights if the repo does not already expose GGUF files.
|
||||
|
||||
## Quick start
|
||||
|
||||
### Install llama.cpp
|
||||
|
||||
```bash
|
||||
# macOS / Linux (simplest)
|
||||
brew install llama.cpp
|
||||
```
|
||||
|
||||
```bash
|
||||
winget install llama.cpp
|
||||
```
|
||||
|
||||
```bash
|
||||
git clone https://github.com/ggml-org/llama.cpp
|
||||
cd llama.cpp
|
||||
cmake -B build
|
||||
cmake --build build --config Release
|
||||
```
|
||||
|
||||
### Run directly from the Hugging Face Hub
|
||||
|
||||
```bash
|
||||
llama-cli -hf bartowski/Llama-3.2-3B-Instruct-GGUF:Q8_0
|
||||
```
|
||||
|
||||
```bash
|
||||
llama-server -hf bartowski/Llama-3.2-3B-Instruct-GGUF:Q8_0
|
||||
```
|
||||
|
||||
### Run an exact GGUF file from the Hub
|
||||
|
||||
Use this when the tree API shows custom file naming or the exact HF snippet is missing.
|
||||
|
||||
```bash
|
||||
llama-server \
|
||||
--hf-repo microsoft/Phi-3-mini-4k-instruct-gguf \
|
||||
--hf-file Phi-3-mini-4k-instruct-q4.gguf \
|
||||
-c 4096
|
||||
```
|
||||
|
||||
### OpenAI-compatible server check
|
||||
|
||||
```bash
|
||||
curl http://localhost:8080/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"messages": [
|
||||
{"role": "user", "content": "Write a limerick about Python exceptions"}
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
## Python bindings (llama-cpp-python)
|
||||
|
||||
`pip install llama-cpp-python` (CUDA: `CMAKE_ARGS="-DGGML_CUDA=on" pip install llama-cpp-python --force-reinstall --no-cache-dir`; Metal: `CMAKE_ARGS="-DGGML_METAL=on" ...`).
|
||||
|
||||
### Basic generation
|
||||
|
||||
```python
|
||||
from llama_cpp import Llama
|
||||
|
||||
llm = Llama(
|
||||
model_path="./model-q4_k_m.gguf",
|
||||
n_ctx=4096,
|
||||
n_gpu_layers=35, # 0 for CPU, 99 to offload everything
|
||||
n_threads=8,
|
||||
)
|
||||
|
||||
out = llm("What is machine learning?", max_tokens=256, temperature=0.7)
|
||||
print(out["choices"][0]["text"])
|
||||
```
|
||||
|
||||
### Chat + streaming
|
||||
|
||||
```python
|
||||
llm = Llama(
|
||||
model_path="./model-q4_k_m.gguf",
|
||||
n_ctx=4096,
|
||||
n_gpu_layers=35,
|
||||
chat_format="llama-3", # or "chatml", "mistral", etc.
|
||||
)
|
||||
|
||||
resp = llm.create_chat_completion(
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "What is Python?"},
|
||||
],
|
||||
max_tokens=256,
|
||||
)
|
||||
print(resp["choices"][0]["message"]["content"])
|
||||
|
||||
# Streaming
|
||||
for chunk in llm("Explain quantum computing:", max_tokens=256, stream=True):
|
||||
print(chunk["choices"][0]["text"], end="", flush=True)
|
||||
```
|
||||
|
||||
### Embeddings
|
||||
|
||||
```python
|
||||
llm = Llama(model_path="./model-q4_k_m.gguf", embedding=True, n_gpu_layers=35)
|
||||
vec = llm.embed("This is a test sentence.")
|
||||
print(f"Embedding dimension: {len(vec)}")
|
||||
```
|
||||
|
||||
You can also load a GGUF straight from the Hub:
|
||||
|
||||
```python
|
||||
llm = Llama.from_pretrained(
|
||||
repo_id="bartowski/Llama-3.2-3B-Instruct-GGUF",
|
||||
filename="*Q4_K_M.gguf",
|
||||
n_gpu_layers=35,
|
||||
)
|
||||
```
|
||||
|
||||
## Choosing a quant
|
||||
|
||||
Use the Hub page first, generic heuristics second.
|
||||
|
||||
- Prefer the exact quant that HF marks as compatible for the user's hardware profile.
|
||||
- For general chat, start with `Q4_K_M`.
|
||||
- For code or technical work, prefer `Q5_K_M` or `Q6_K` if memory allows.
|
||||
- For very tight RAM budgets, consider `Q3_K_M`, `IQ` variants, or `Q2` variants only if the user explicitly prioritizes fit over quality.
|
||||
- For multimodal repos, mention `mmproj-*.gguf` separately. The projector is not the main model file.
|
||||
- Do not normalize repo-native labels. If the page says `UD-Q4_K_M`, report `UD-Q4_K_M`.
|
||||
|
||||
## Extracting available GGUFs from a repo
|
||||
|
||||
When the user asks what GGUFs exist, return:
|
||||
|
||||
- filename
|
||||
- file size
|
||||
- quant label
|
||||
- whether it is a main model or an auxiliary projector
|
||||
|
||||
Ignore unless requested:
|
||||
|
||||
- README
|
||||
- BF16 shard files
|
||||
- imatrix blobs or calibration artifacts
|
||||
|
||||
Use the tree API for this step:
|
||||
|
||||
- `https://huggingface.co/api/models/<repo>/tree/main?recursive=true`
|
||||
|
||||
For a repo like `unsloth/Qwen3.6-35B-A3B-GGUF`, the local-app page can show quant chips such as `UD-Q4_K_M`, `UD-Q5_K_M`, `UD-Q6_K`, and `Q8_0`, while the tree API exposes exact file paths such as `Qwen3.6-35B-A3B-UD-Q4_K_M.gguf` and `Qwen3.6-35B-A3B-Q8_0.gguf` with byte sizes. Use the tree API to turn a quant label into an exact filename.
|
||||
|
||||
## Search patterns
|
||||
|
||||
Use these URL shapes directly:
|
||||
|
||||
```text
|
||||
https://huggingface.co/models?apps=llama.cpp&sort=trending
|
||||
https://huggingface.co/models?search=<term>&apps=llama.cpp&sort=trending
|
||||
https://huggingface.co/models?search=<term>&apps=llama.cpp&num_parameters=min:0,max:24B&sort=trending
|
||||
https://huggingface.co/<repo>?local-app=llama.cpp
|
||||
https://huggingface.co/api/models/<repo>/tree/main?recursive=true
|
||||
https://huggingface.co/<repo>/tree/main
|
||||
```
|
||||
|
||||
## Output format
|
||||
|
||||
When answering discovery requests, prefer a compact structured result like:
|
||||
|
||||
```text
|
||||
Repo: <repo>
|
||||
Recommended quant from HF: <label> (<size>)
|
||||
llama-server: <command>
|
||||
Other GGUFs:
|
||||
- <filename> - <size>
|
||||
- <filename> - <size>
|
||||
Source URLs:
|
||||
- <local-app URL>
|
||||
- <tree API URL>
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- **[hub-discovery.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\llama-cpp/references/hub-discovery.md)** - URL-only Hugging Face workflows, search patterns, GGUF extraction, and command reconstruction
|
||||
- **[advanced-usage.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\llama-cpp/references/advanced-usage.md)** — speculative decoding, batched inference, grammar-constrained generation, LoRA, multi-GPU, custom builds, benchmark scripts
|
||||
- **[quantization.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\llama-cpp/references/quantization.md)** — quant quality tradeoffs, when to use Q4/Q5/Q6/IQ, model size scaling, imatrix
|
||||
- **[server.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\llama-cpp/references/server.md)** — direct-from-Hub server launch, OpenAI API endpoints, Docker deployment, NGINX load balancing, monitoring
|
||||
- **[optimization.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\llama-cpp/references/optimization.md)** — CPU threading, BLAS, GPU offload heuristics, batch tuning, benchmarks
|
||||
- **[troubleshooting.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\llama-cpp/references/troubleshooting.md)** — install/convert/quantize/inference/server issues, Apple Silicon, debugging
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/ggml-org/llama.cpp
|
||||
- **Hugging Face GGUF + llama.cpp docs**: https://huggingface.co/docs/hub/gguf-llamacpp
|
||||
- **Hugging Face Local Apps docs**: https://huggingface.co/docs/hub/main/local-apps
|
||||
- **Hugging Face Local Agents docs**: https://huggingface.co/docs/hub/agents-local
|
||||
- **Example local-app page**: https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF?local-app=llama.cpp
|
||||
- **Example tree API**: https://huggingface.co/api/models/unsloth/Qwen3.6-35B-A3B-GGUF/tree/main?recursive=true
|
||||
- **Example llama.cpp search**: https://huggingface.co/models?num_parameters=min:0,max:24B&apps=llama.cpp&sort=trending
|
||||
- **License**: MIT
|
||||
@@ -0,0 +1,679 @@
|
||||
---
|
||||
title: "Outlines — Outlines: structured JSON/regex/Pydantic LLM generation"
|
||||
sidebar_label: "Outlines"
|
||||
description: "Outlines: structured JSON/regex/Pydantic LLM generation"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Outlines
|
||||
|
||||
Outlines: structured JSON/regex/Pydantic LLM generation.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/outlines` |
|
||||
| Path | `optional-skills/mlops\inference\outlines` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `outlines`, `transformers`, `vllm`, `pydantic` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Prompt Engineering`, `Outlines`, `Structured Generation`, `JSON Schema`, `Pydantic`, `Local Models`, `Grammar-Based Generation`, `vLLM`, `Transformers`, `Type Safety` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Outlines: Structured Text Generation
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use Outlines when you need to:
|
||||
- **Guarantee valid JSON/XML/code** structure during generation
|
||||
- **Use Pydantic models** for type-safe outputs
|
||||
- **Support local models** (Transformers, llama.cpp, vLLM)
|
||||
- **Maximize inference speed** with zero-overhead structured generation
|
||||
- **Generate against JSON schemas** automatically
|
||||
- **Control token sampling** at the grammar level
|
||||
|
||||
**GitHub Stars**: 12,000+ | **From**: dottxt.ai (formerly .txt)
|
||||
|
||||
> **API note (Outlines 1.x):** This skill targets the current v1 API.
|
||||
> The pre-1.0 helpers (`outlines.models.transformers(...)`,
|
||||
> `outlines.generate.json/choice/regex/...`) have been **removed**. In v1 you
|
||||
> create a model with `outlines.from_transformers(...)` (or `from_vllm`,
|
||||
> `from_llamacpp`, `from_openai`) and then **call the model directly** with an
|
||||
> output type: `model(prompt, output_type)`. JSON/Pydantic outputs are returned
|
||||
> as a **JSON string** — validate with `YourModel.model_validate_json(result)`.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Base installation
|
||||
pip install outlines
|
||||
|
||||
# With specific backends
|
||||
pip install outlines transformers # Hugging Face models
|
||||
pip install outlines llama-cpp-python # llama.cpp
|
||||
pip install outlines vllm # vLLM for high-throughput
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Basic Example: Classification
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from typing import Literal
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
|
||||
|
||||
# v1: wrap a Transformers model + tokenizer
|
||||
model = outlines.from_transformers(
|
||||
AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto"),
|
||||
AutoTokenizer.from_pretrained(MODEL_NAME),
|
||||
)
|
||||
|
||||
# Call the model directly with an output type
|
||||
prompt = "Sentiment of 'This product is amazing!': "
|
||||
sentiment = model(prompt, Literal["positive", "negative", "neutral"])
|
||||
|
||||
print(sentiment) # "positive" (guaranteed one of these)
|
||||
```
|
||||
|
||||
### With Pydantic Models
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
import outlines
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
class User(BaseModel):
|
||||
name: str
|
||||
age: int
|
||||
email: str
|
||||
|
||||
MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
|
||||
model = outlines.from_transformers(
|
||||
AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto"),
|
||||
AutoTokenizer.from_pretrained(MODEL_NAME),
|
||||
)
|
||||
|
||||
# Generate structured output (returns a JSON string)
|
||||
prompt = "Extract user: John Doe, 30 years old, john@example.com"
|
||||
result = model(prompt, User, max_new_tokens=200)
|
||||
|
||||
user = User.model_validate_json(result) # parse into the Pydantic model
|
||||
print(user.name) # "John Doe"
|
||||
print(user.age) # 30
|
||||
print(user.email) # "john@example.com"
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### 1. Constrained Token Sampling
|
||||
|
||||
Outlines constrains token generation at the logit level using a compiled
|
||||
automaton derived from your output type.
|
||||
|
||||
**How it works:**
|
||||
1. Convert the output type (JSON/Pydantic/regex/`Literal`) to a schema/grammar
|
||||
2. Compile the grammar into a token-level automaton
|
||||
3. Filter invalid tokens at each step during generation
|
||||
4. Fast-forward when only one valid token exists
|
||||
|
||||
**Benefits:**
|
||||
- **Zero overhead**: Filtering happens at token level
|
||||
- **Speed improvement**: Fast-forward through deterministic paths
|
||||
- **Guaranteed validity**: Invalid outputs impossible
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from pydantic import BaseModel
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
class Person(BaseModel):
|
||||
name: str
|
||||
age: int
|
||||
|
||||
model = outlines.from_transformers(
|
||||
AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct", device_map="auto"),
|
||||
AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct"),
|
||||
)
|
||||
|
||||
result = model("Generate person: Alice, 25", Person)
|
||||
person = Person.model_validate_json(result)
|
||||
```
|
||||
|
||||
### 2. Output Types
|
||||
|
||||
In v1 you pass the desired **output type** directly as the second argument.
|
||||
|
||||
#### Multiple choice (`Literal`)
|
||||
|
||||
```python
|
||||
from typing import Literal
|
||||
|
||||
sentiment = model("Review: This is great!", Literal["positive", "negative", "neutral"])
|
||||
# Result: one of the three choices
|
||||
```
|
||||
|
||||
#### JSON via Pydantic
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
|
||||
class Product(BaseModel):
|
||||
name: str
|
||||
price: float
|
||||
in_stock: bool
|
||||
|
||||
result = model("Extract: iPhone 15, $999, available", Product)
|
||||
product = Product.model_validate_json(result) # valid Product instance
|
||||
```
|
||||
|
||||
#### Regex (pass a regex string)
|
||||
|
||||
```python
|
||||
# Generate text matching a regex pattern
|
||||
phone = model("Generate phone number:", r"[0-9]{3}-[0-9]{3}-[0-9]{4}")
|
||||
# Result: "555-123-4567" (guaranteed to match the pattern)
|
||||
```
|
||||
|
||||
#### Numeric types
|
||||
|
||||
```python
|
||||
# Pass the Python type directly
|
||||
age = model("Person's age:", int) # guaranteed integer
|
||||
price = model("Product price:", float) # guaranteed float
|
||||
```
|
||||
|
||||
### 3. Model Backends
|
||||
|
||||
Outlines supports multiple local and API-based backends via `from_*` factories.
|
||||
|
||||
#### Transformers (Hugging Face)
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
model = outlines.from_transformers(
|
||||
AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct", device_map="auto"),
|
||||
AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct"),
|
||||
)
|
||||
|
||||
result = model(prompt, YourModel)
|
||||
```
|
||||
|
||||
#### llama.cpp
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from llama_cpp import Llama
|
||||
|
||||
llm = Llama("./models/llama-3.1-8b-instruct.Q4_K_M.gguf", n_gpu_layers=35, n_ctx=4096)
|
||||
model = outlines.from_llamacpp(llm)
|
||||
|
||||
result = model(prompt, YourModel)
|
||||
```
|
||||
|
||||
#### vLLM (High Throughput)
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from vllm import LLM
|
||||
|
||||
llm = LLM("meta-llama/Llama-3.1-8B-Instruct", tensor_parallel_size=2)
|
||||
model = outlines.from_vllm(llm)
|
||||
|
||||
result = model(prompt, YourModel)
|
||||
```
|
||||
|
||||
#### OpenAI (server-side constrained JSON)
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from openai import OpenAI
|
||||
|
||||
client = OpenAI()
|
||||
model = outlines.from_openai(client, "gpt-4o-mini")
|
||||
|
||||
# API backends support JSON-schema style structured output
|
||||
result = model(prompt, YourModel)
|
||||
```
|
||||
|
||||
### 4. Pydantic Integration
|
||||
|
||||
Outlines has first-class Pydantic support with automatic schema translation.
|
||||
Generation returns a JSON string; call `model_validate_json` to get an instance.
|
||||
|
||||
#### Basic Models
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class Article(BaseModel):
|
||||
title: str = Field(description="Article title")
|
||||
author: str = Field(description="Author name")
|
||||
word_count: int = Field(description="Number of words", gt=0)
|
||||
tags: list[str] = Field(description="List of tags")
|
||||
|
||||
result = model("Generate article about AI", Article, max_new_tokens=300)
|
||||
article = Article.model_validate_json(result)
|
||||
print(article.title)
|
||||
print(article.word_count) # Guaranteed > 0
|
||||
```
|
||||
|
||||
#### Nested Models
|
||||
|
||||
```python
|
||||
class Address(BaseModel):
|
||||
street: str
|
||||
city: str
|
||||
country: str
|
||||
|
||||
class Person(BaseModel):
|
||||
name: str
|
||||
age: int
|
||||
address: Address # Nested model
|
||||
|
||||
result = model("Generate person in New York", Person)
|
||||
person = Person.model_validate_json(result)
|
||||
print(person.address.city) # "New York"
|
||||
```
|
||||
|
||||
#### Enums and Literals
|
||||
|
||||
```python
|
||||
from enum import Enum
|
||||
from typing import Literal
|
||||
|
||||
class Status(str, Enum):
|
||||
PENDING = "pending"
|
||||
APPROVED = "approved"
|
||||
REJECTED = "rejected"
|
||||
|
||||
class Application(BaseModel):
|
||||
applicant: str
|
||||
status: Status # Must be one of enum values
|
||||
priority: Literal["low", "medium", "high"] # Must be one of literals
|
||||
|
||||
result = model("Generate application", Application)
|
||||
app = Application.model_validate_json(result)
|
||||
print(app.status) # Status.PENDING (or APPROVED/REJECTED)
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Pattern 1: Data Extraction
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
import outlines
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
class CompanyInfo(BaseModel):
|
||||
name: str
|
||||
founded_year: int
|
||||
industry: str
|
||||
employees: int
|
||||
|
||||
model = outlines.from_transformers(
|
||||
AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct", device_map="auto"),
|
||||
AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct"),
|
||||
)
|
||||
|
||||
text = """
|
||||
Apple Inc. was founded in 1976 in the technology industry.
|
||||
The company employs approximately 164,000 people worldwide.
|
||||
"""
|
||||
|
||||
prompt = f"Extract company information:\n{text}\n\nCompany:"
|
||||
company = CompanyInfo.model_validate_json(model(prompt, CompanyInfo, max_new_tokens=200))
|
||||
|
||||
print(f"Name: {company.name}")
|
||||
print(f"Founded: {company.founded_year}")
|
||||
print(f"Industry: {company.industry}")
|
||||
print(f"Employees: {company.employees}")
|
||||
```
|
||||
|
||||
### Pattern 2: Classification
|
||||
|
||||
```python
|
||||
from typing import Literal
|
||||
from pydantic import BaseModel
|
||||
|
||||
# Binary classification
|
||||
result = model("Email: Buy now! 50% off!", Literal["spam", "not_spam"])
|
||||
|
||||
# Multi-class classification
|
||||
category = model(
|
||||
"Article: Apple announces new iPhone...",
|
||||
Literal["technology", "business", "sports", "entertainment"],
|
||||
)
|
||||
|
||||
# With confidence
|
||||
class Classification(BaseModel):
|
||||
label: Literal["positive", "negative", "neutral"]
|
||||
confidence: float
|
||||
|
||||
out = model("Review: This product is okay, nothing special", Classification)
|
||||
result = Classification.model_validate_json(out)
|
||||
```
|
||||
|
||||
### Pattern 3: Structured Forms
|
||||
|
||||
```python
|
||||
class UserProfile(BaseModel):
|
||||
full_name: str
|
||||
age: int
|
||||
email: str
|
||||
phone: str
|
||||
country: str
|
||||
interests: list[str]
|
||||
|
||||
prompt = """
|
||||
Extract user profile from:
|
||||
Name: Alice Johnson
|
||||
Age: 28
|
||||
Email: alice@example.com
|
||||
Phone: 555-0123
|
||||
Country: USA
|
||||
Interests: hiking, photography, cooking
|
||||
"""
|
||||
|
||||
profile = UserProfile.model_validate_json(model(prompt, UserProfile, max_new_tokens=250))
|
||||
print(profile.full_name)
|
||||
print(profile.interests) # ["hiking", "photography", "cooking"]
|
||||
```
|
||||
|
||||
### Pattern 4: Multi-Entity Extraction
|
||||
|
||||
```python
|
||||
from typing import Literal
|
||||
|
||||
class Entity(BaseModel):
|
||||
name: str
|
||||
type: Literal["PERSON", "ORGANIZATION", "LOCATION"]
|
||||
|
||||
class DocumentEntities(BaseModel):
|
||||
entities: list[Entity]
|
||||
|
||||
text = "Tim Cook met with Satya Nadella at Microsoft headquarters in Redmond."
|
||||
prompt = f"Extract entities from: {text}"
|
||||
|
||||
result = DocumentEntities.model_validate_json(model(prompt, DocumentEntities, max_new_tokens=300))
|
||||
for entity in result.entities:
|
||||
print(f"{entity.name} ({entity.type})")
|
||||
```
|
||||
|
||||
### Pattern 5: Code Generation
|
||||
|
||||
```python
|
||||
class PythonFunction(BaseModel):
|
||||
function_name: str
|
||||
parameters: list[str]
|
||||
docstring: str
|
||||
body: str
|
||||
|
||||
prompt = "Generate a Python function to calculate factorial"
|
||||
func = PythonFunction.model_validate_json(model(prompt, PythonFunction, max_new_tokens=300))
|
||||
|
||||
print(f"def {func.function_name}({', '.join(func.parameters)}):")
|
||||
print(f' """{func.docstring}"""')
|
||||
print(f" {func.body}")
|
||||
```
|
||||
|
||||
### Pattern 6: Batch Processing
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
from pydantic import BaseModel
|
||||
|
||||
class Person(BaseModel):
|
||||
name: str
|
||||
age: int
|
||||
|
||||
model = outlines.from_transformers(
|
||||
AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct", device_map="auto"),
|
||||
AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct"),
|
||||
)
|
||||
|
||||
texts = [
|
||||
"John is 30 years old",
|
||||
"Alice is 25 years old",
|
||||
"Bob is 40 years old",
|
||||
]
|
||||
|
||||
# v1 accepts a list of prompts for batched generation
|
||||
prompts = [f"Extract from: {t}" for t in texts]
|
||||
outputs = model(prompts, Person, max_new_tokens=100)
|
||||
people = [Person.model_validate_json(o) for o in outputs]
|
||||
for person in people:
|
||||
print(f"{person.name}: {person.age}")
|
||||
```
|
||||
|
||||
## Backend Configuration
|
||||
|
||||
### Transformers
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
|
||||
MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
|
||||
|
||||
# Basic usage
|
||||
model = outlines.from_transformers(
|
||||
AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto"),
|
||||
AutoTokenizer.from_pretrained(MODEL_NAME),
|
||||
)
|
||||
|
||||
# GPU + dtype configuration is set on the HF model itself
|
||||
import torch
|
||||
model = outlines.from_transformers(
|
||||
AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="cuda", torch_dtype=torch.float16),
|
||||
AutoTokenizer.from_pretrained(MODEL_NAME),
|
||||
)
|
||||
|
||||
# Popular models
|
||||
for name in [
|
||||
"meta-llama/Llama-3.1-8B-Instruct",
|
||||
"mistralai/Mistral-7B-Instruct-v0.3",
|
||||
"Qwen/Qwen2.5-7B-Instruct",
|
||||
]:
|
||||
model = outlines.from_transformers(
|
||||
AutoModelForCausalLM.from_pretrained(name, device_map="auto"),
|
||||
AutoTokenizer.from_pretrained(name),
|
||||
)
|
||||
```
|
||||
|
||||
### llama.cpp
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from llama_cpp import Llama
|
||||
|
||||
# Load GGUF model
|
||||
llm = Llama(
|
||||
"./models/llama-3.1-8b.Q4_K_M.gguf",
|
||||
n_ctx=4096, # Context window
|
||||
n_gpu_layers=35, # GPU layers
|
||||
n_threads=8, # CPU threads
|
||||
)
|
||||
model = outlines.from_llamacpp(llm)
|
||||
|
||||
# Full GPU offload: set n_gpu_layers=-1 on the Llama object
|
||||
```
|
||||
|
||||
### vLLM (Production)
|
||||
|
||||
```python
|
||||
import outlines
|
||||
from vllm import LLM
|
||||
|
||||
# Single GPU
|
||||
model = outlines.from_vllm(LLM("meta-llama/Llama-3.1-8B-Instruct"))
|
||||
|
||||
# Multi-GPU
|
||||
model = outlines.from_vllm(LLM("meta-llama/Llama-3.1-70B-Instruct", tensor_parallel_size=4))
|
||||
|
||||
# With quantization
|
||||
model = outlines.from_vllm(LLM("meta-llama/Llama-3.1-8B-Instruct", quantization="awq"))
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Use Specific Types
|
||||
|
||||
```python
|
||||
# ✅ Good: Specific types
|
||||
class Product(BaseModel):
|
||||
name: str
|
||||
price: float # Not str
|
||||
quantity: int # Not str
|
||||
in_stock: bool # Not str
|
||||
|
||||
# ❌ Bad: Everything as string
|
||||
class Product(BaseModel):
|
||||
name: str
|
||||
price: str # Should be float
|
||||
quantity: str # Should be int
|
||||
```
|
||||
|
||||
### 2. Add Constraints
|
||||
|
||||
```python
|
||||
from pydantic import Field
|
||||
|
||||
# ✅ Good: With constraints
|
||||
class User(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
age: int = Field(ge=0, le=120)
|
||||
email: str = Field(pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$")
|
||||
|
||||
# ❌ Bad: No constraints
|
||||
class User(BaseModel):
|
||||
name: str
|
||||
age: int
|
||||
email: str
|
||||
```
|
||||
|
||||
### 3. Use Enums for Categories
|
||||
|
||||
```python
|
||||
# ✅ Good: Enum for fixed set
|
||||
class Priority(str, Enum):
|
||||
LOW = "low"
|
||||
MEDIUM = "medium"
|
||||
HIGH = "high"
|
||||
|
||||
class Task(BaseModel):
|
||||
title: str
|
||||
priority: Priority
|
||||
|
||||
# ❌ Bad: Free-form string
|
||||
class Task(BaseModel):
|
||||
title: str
|
||||
priority: str # Can be anything
|
||||
```
|
||||
|
||||
### 4. Provide Context in Prompts
|
||||
|
||||
```python
|
||||
# ✅ Good: Clear context
|
||||
prompt = """
|
||||
Extract product information from the following text.
|
||||
Text: iPhone 15 Pro costs $999 and is currently in stock.
|
||||
Product:
|
||||
"""
|
||||
|
||||
# ❌ Bad: Minimal context
|
||||
prompt = "iPhone 15 Pro costs $999 and is currently in stock."
|
||||
```
|
||||
|
||||
### 5. Handle Optional Fields
|
||||
|
||||
```python
|
||||
from typing import Optional
|
||||
|
||||
# ✅ Good: Optional fields for incomplete data
|
||||
class Article(BaseModel):
|
||||
title: str # Required
|
||||
author: Optional[str] = None # Optional
|
||||
date: Optional[str] = None # Optional
|
||||
tags: list[str] = [] # Default empty list
|
||||
|
||||
# Can succeed even if author/date missing
|
||||
```
|
||||
|
||||
### 6. Always Validate JSON Output
|
||||
|
||||
```python
|
||||
# v1 returns a JSON string for Pydantic/JSON output types.
|
||||
result = model(prompt, Article) # str
|
||||
article = Article.model_validate_json(result) # Article instance
|
||||
```
|
||||
|
||||
## Comparison to Alternatives
|
||||
|
||||
| Feature | Outlines | Instructor | Guidance | LMQL |
|
||||
|---------|----------|------------|----------|------|
|
||||
| Pydantic Support | ✅ Native | ✅ Native | ✅ Yes | ❌ No |
|
||||
| JSON Schema | ✅ Yes | ✅ Yes | ✅ Yes | ✅ Yes |
|
||||
| Regex Constraints | ✅ Yes | ❌ No | ✅ Yes | ✅ Yes |
|
||||
| Local Models | ✅ Full | ⚠️ Limited | ✅ Full | ✅ Full |
|
||||
| API Models | ✅ Yes | ✅ Full | ✅ Yes | ✅ Full |
|
||||
| Zero Overhead | ✅ Yes | ❌ No | ⚠️ Partial | ✅ Yes |
|
||||
| Automatic Retrying | ❌ No | ✅ Yes | ❌ No | ❌ No |
|
||||
| Learning Curve | Low | Low | Low | High |
|
||||
|
||||
**When to choose Outlines:**
|
||||
- Using local models (Transformers, llama.cpp, vLLM)
|
||||
- Need maximum inference speed
|
||||
- Want Pydantic model support
|
||||
- Require zero-overhead structured generation
|
||||
- Control token sampling process
|
||||
|
||||
**When to choose alternatives:**
|
||||
- Instructor: Need API models with automatic retrying
|
||||
- Guidance: Need token healing and complex workflows
|
||||
- LMQL: Prefer declarative query syntax
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
**Speed:**
|
||||
- **Zero overhead**: Structured generation as fast as unconstrained
|
||||
- **Fast-forward optimization**: Skips deterministic tokens
|
||||
- **1.2-2x faster** than post-generation validation approaches
|
||||
|
||||
**Memory:**
|
||||
- Automaton compiled once per output type (cached)
|
||||
- Minimal runtime overhead
|
||||
- Efficient with vLLM for high throughput
|
||||
|
||||
**Accuracy:**
|
||||
- **100% valid outputs** (guaranteed by the constrained automaton)
|
||||
- No retry loops needed
|
||||
- Deterministic token filtering
|
||||
|
||||
## Resources
|
||||
|
||||
- **Documentation**: https://dottxt-ai.github.io/outlines/
|
||||
- **GitHub**: https://github.com/dottxt-ai/outlines (12k+ stars)
|
||||
- **Discord**: https://discord.gg/R9DSu34mGd
|
||||
- **Blog**: https://blog.dottxt.co
|
||||
|
||||
## See Also
|
||||
|
||||
- `references/json_generation.md` - Comprehensive JSON and Pydantic patterns
|
||||
- `references/backends.md` - Backend-specific configuration
|
||||
- `references/examples.md` - Production-ready examples
|
||||
@@ -0,0 +1,387 @@
|
||||
---
|
||||
title: "Serving Llms Vllm — vLLM: high-throughput LLM serving, OpenAI API, quantization"
|
||||
sidebar_label: "Serving Llms Vllm"
|
||||
description: "vLLM: high-throughput LLM serving, OpenAI API, quantization"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Serving Llms Vllm
|
||||
|
||||
vLLM: high-throughput LLM serving, OpenAI API, quantization.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/serving-llms-vllm` |
|
||||
| Path | `optional-skills/mlops\inference\serving-llms-vllm` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `vllm`, `torch`, `transformers` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `vLLM`, `Inference Serving`, `PagedAttention`, `Continuous Batching`, `High Throughput`, `Production`, `OpenAI API`, `Quantization`, `Tensor Parallelism` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# vLLM - High-Performance LLM Serving
|
||||
|
||||
## When to use
|
||||
|
||||
Use when deploying production LLM APIs, optimizing inference latency/throughput, or serving models with limited GPU memory. Supports OpenAI-compatible endpoints, quantization (GPTQ/AWQ/FP8), and tensor parallelism.
|
||||
|
||||
## Quick start
|
||||
|
||||
vLLM achieves 24x higher throughput than standard transformers through PagedAttention (block-based KV cache) and continuous batching (mixing prefill/decode requests).
|
||||
|
||||
**Installation**:
|
||||
```bash
|
||||
pip install vllm
|
||||
```
|
||||
|
||||
**Basic offline inference**:
|
||||
```python
|
||||
from vllm import LLM, SamplingParams
|
||||
|
||||
llm = LLM(model="meta-llama/Meta-Llama-3-8B-Instruct")
|
||||
sampling = SamplingParams(temperature=0.7, max_tokens=256)
|
||||
|
||||
outputs = llm.generate(["Explain quantum computing"], sampling)
|
||||
print(outputs[0].outputs[0].text)
|
||||
```
|
||||
|
||||
**OpenAI-compatible server**:
|
||||
```bash
|
||||
vllm serve meta-llama/Meta-Llama-3-8B-Instruct
|
||||
|
||||
# Query with OpenAI SDK
|
||||
python -c "
|
||||
from openai import OpenAI
|
||||
client = OpenAI(base_url='http://localhost:8000/v1', api_key='EMPTY')
|
||||
print(client.chat.completions.create(
|
||||
model='meta-llama/Meta-Llama-3-8B-Instruct',
|
||||
messages=[{'role': 'user', 'content': 'Hello!'}]
|
||||
).choices[0].message.content)
|
||||
"
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: Production API deployment
|
||||
|
||||
Copy this checklist and track progress:
|
||||
|
||||
```
|
||||
Deployment Progress:
|
||||
- [ ] Step 1: Configure server settings
|
||||
- [ ] Step 2: Test with limited traffic
|
||||
- [ ] Step 3: Enable monitoring
|
||||
- [ ] Step 4: Deploy to production
|
||||
- [ ] Step 5: Verify performance metrics
|
||||
```
|
||||
|
||||
**Step 1: Configure server settings**
|
||||
|
||||
Choose configuration based on your model size:
|
||||
|
||||
```bash
|
||||
# For 7B-13B models on single GPU
|
||||
vllm serve meta-llama/Meta-Llama-3-8B-Instruct \
|
||||
--gpu-memory-utilization 0.9 \
|
||||
--max-model-len 8192 \
|
||||
--port 8000
|
||||
|
||||
# For 30B-70B models with tensor parallelism
|
||||
vllm serve meta-llama/Meta-Llama-3-70B-Instruct \
|
||||
--tensor-parallel-size 4 \
|
||||
--gpu-memory-utilization 0.9 \
|
||||
--quantization awq \
|
||||
--port 8000
|
||||
|
||||
# For production with caching (Prometheus metrics are exposed
|
||||
# automatically at /metrics on the API port)
|
||||
vllm serve meta-llama/Meta-Llama-3-8B-Instruct \
|
||||
--gpu-memory-utilization 0.9 \
|
||||
--enable-prefix-caching \
|
||||
--port 8000 \
|
||||
--host 0.0.0.0
|
||||
```
|
||||
|
||||
**Step 2: Test with limited traffic**
|
||||
|
||||
Run load test before production:
|
||||
|
||||
```bash
|
||||
# Install load testing tool
|
||||
pip install locust
|
||||
|
||||
# Create test_load.py with sample requests
|
||||
# Run: locust -f test_load.py --host http://localhost:8000
|
||||
```
|
||||
|
||||
Verify TTFT (time to first token) < 500ms and throughput > 100 req/sec.
|
||||
|
||||
**Step 3: Enable monitoring**
|
||||
|
||||
vLLM exposes Prometheus metrics at `/metrics` on the API port (default 8000):
|
||||
|
||||
```bash
|
||||
curl http://localhost:8000/metrics | grep vllm
|
||||
```
|
||||
|
||||
Key metrics to monitor:
|
||||
- `vllm:time_to_first_token_seconds` - Latency
|
||||
- `vllm:num_requests_running` - Active requests
|
||||
- `vllm:gpu_cache_usage_perc` - KV cache utilization
|
||||
|
||||
**Step 4: Deploy to production**
|
||||
|
||||
Use Docker for consistent deployment:
|
||||
|
||||
```bash
|
||||
# Run vLLM in Docker
|
||||
docker run --gpus all -p 8000:8000 \
|
||||
vllm/vllm-openai:latest \
|
||||
--model meta-llama/Meta-Llama-3-8B-Instruct \
|
||||
--gpu-memory-utilization 0.9 \
|
||||
--enable-prefix-caching
|
||||
```
|
||||
|
||||
**Step 5: Verify performance metrics**
|
||||
|
||||
Check that deployment meets targets:
|
||||
- TTFT < 500ms (for short prompts)
|
||||
- Throughput > target req/sec
|
||||
- GPU utilization > 80%
|
||||
- No OOM errors in logs
|
||||
|
||||
### Workflow 2: Offline batch inference
|
||||
|
||||
For processing large datasets without server overhead.
|
||||
|
||||
Copy this checklist:
|
||||
|
||||
```
|
||||
Batch Processing:
|
||||
- [ ] Step 1: Prepare input data
|
||||
- [ ] Step 2: Configure LLM engine
|
||||
- [ ] Step 3: Run batch inference
|
||||
- [ ] Step 4: Process results
|
||||
```
|
||||
|
||||
**Step 1: Prepare input data**
|
||||
|
||||
```python
|
||||
# Load prompts from file
|
||||
prompts = []
|
||||
with open("prompts.txt") as f:
|
||||
prompts = [line.strip() for line in f]
|
||||
|
||||
print(f"Loaded {len(prompts)} prompts")
|
||||
```
|
||||
|
||||
**Step 2: Configure LLM engine**
|
||||
|
||||
```python
|
||||
from vllm import LLM, SamplingParams
|
||||
|
||||
llm = LLM(
|
||||
model="meta-llama/Meta-Llama-3-8B-Instruct",
|
||||
tensor_parallel_size=2, # Use 2 GPUs
|
||||
gpu_memory_utilization=0.9,
|
||||
max_model_len=4096
|
||||
)
|
||||
|
||||
sampling = SamplingParams(
|
||||
temperature=0.7,
|
||||
top_p=0.95,
|
||||
max_tokens=512,
|
||||
stop=["</s>", "\n\n"]
|
||||
)
|
||||
```
|
||||
|
||||
**Step 3: Run batch inference**
|
||||
|
||||
vLLM automatically batches requests for efficiency:
|
||||
|
||||
```python
|
||||
# Process all prompts in one call
|
||||
outputs = llm.generate(prompts, sampling)
|
||||
|
||||
# vLLM handles batching internally
|
||||
# No need to manually chunk prompts
|
||||
```
|
||||
|
||||
**Step 4: Process results**
|
||||
|
||||
```python
|
||||
# Extract generated text
|
||||
results = []
|
||||
for output in outputs:
|
||||
prompt = output.prompt
|
||||
generated = output.outputs[0].text
|
||||
results.append({
|
||||
"prompt": prompt,
|
||||
"generated": generated,
|
||||
"tokens": len(output.outputs[0].token_ids)
|
||||
})
|
||||
|
||||
# Save to file
|
||||
import json
|
||||
with open("results.jsonl", "w") as f:
|
||||
for result in results:
|
||||
f.write(json.dumps(result) + "\n")
|
||||
|
||||
print(f"Processed {len(results)} prompts")
|
||||
```
|
||||
|
||||
### Workflow 3: Quantized model serving
|
||||
|
||||
Fit large models in limited GPU memory.
|
||||
|
||||
```
|
||||
Quantization Setup:
|
||||
- [ ] Step 1: Choose quantization method
|
||||
- [ ] Step 2: Find or create quantized model
|
||||
- [ ] Step 3: Launch with quantization flag
|
||||
- [ ] Step 4: Verify accuracy
|
||||
```
|
||||
|
||||
**Step 1: Choose quantization method**
|
||||
|
||||
- **AWQ**: Best for 70B models, minimal accuracy loss
|
||||
- **GPTQ**: Wide model support, good compression
|
||||
- **FP8**: Fastest on H100 GPUs
|
||||
|
||||
**Step 2: Find or create quantized model**
|
||||
|
||||
Use pre-quantized models from HuggingFace:
|
||||
|
||||
```bash
|
||||
# Search for AWQ models
|
||||
# Example: TheBloke/Llama-2-70B-AWQ
|
||||
```
|
||||
|
||||
**Step 3: Launch with quantization flag**
|
||||
|
||||
```bash
|
||||
# Using pre-quantized model
|
||||
vllm serve TheBloke/Llama-2-70B-AWQ \
|
||||
--quantization awq \
|
||||
--tensor-parallel-size 1 \
|
||||
--gpu-memory-utilization 0.95
|
||||
|
||||
# Results: 70B model in ~40GB VRAM
|
||||
```
|
||||
|
||||
**Step 4: Verify accuracy**
|
||||
|
||||
Test outputs match expected quality:
|
||||
|
||||
```python
|
||||
# Compare quantized vs non-quantized responses
|
||||
# Verify task-specific performance unchanged
|
||||
```
|
||||
|
||||
## When to use vs alternatives
|
||||
|
||||
**Use vLLM when:**
|
||||
- Deploying production LLM APIs (100+ req/sec)
|
||||
- Serving OpenAI-compatible endpoints
|
||||
- Limited GPU memory but need large models
|
||||
- Multi-user applications (chatbots, assistants)
|
||||
- Need low latency with high throughput
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **llama.cpp**: CPU/edge inference, single-user
|
||||
- **HuggingFace transformers**: Research, prototyping, one-off generation
|
||||
- **TensorRT-LLM**: NVIDIA-only, need absolute maximum performance
|
||||
- **Text-Generation-Inference**: Already in HuggingFace ecosystem
|
||||
|
||||
## Common issues
|
||||
|
||||
**Issue: Out of memory during model loading**
|
||||
|
||||
Reduce memory usage:
|
||||
```bash
|
||||
vllm serve MODEL \
|
||||
--gpu-memory-utilization 0.7 \
|
||||
--max-model-len 4096
|
||||
```
|
||||
|
||||
Or use quantization:
|
||||
```bash
|
||||
vllm serve MODEL --quantization awq
|
||||
```
|
||||
|
||||
**Issue: Slow first token (TTFT > 1 second)**
|
||||
|
||||
Enable prefix caching for repeated prompts:
|
||||
```bash
|
||||
vllm serve MODEL --enable-prefix-caching
|
||||
```
|
||||
|
||||
For long prompts, enable chunked prefill:
|
||||
```bash
|
||||
vllm serve MODEL --enable-chunked-prefill
|
||||
```
|
||||
|
||||
**Issue: Model not found error**
|
||||
|
||||
Use `--trust-remote-code` for custom models:
|
||||
```bash
|
||||
vllm serve MODEL --trust-remote-code
|
||||
```
|
||||
|
||||
**Issue: Low throughput (<50 req/sec)**
|
||||
|
||||
Increase concurrent sequences:
|
||||
```bash
|
||||
vllm serve MODEL --max-num-seqs 512
|
||||
```
|
||||
|
||||
Check GPU utilization with `nvidia-smi` - should be >80%.
|
||||
|
||||
**Issue: Inference slower than expected**
|
||||
|
||||
Verify tensor parallelism uses power of 2 GPUs:
|
||||
```bash
|
||||
vllm serve MODEL --tensor-parallel-size 4 # Not 3
|
||||
```
|
||||
|
||||
Enable speculative decoding for faster generation (pass config as JSON;
|
||||
`--speculative-model` was removed in favor of `--speculative-config`):
|
||||
```bash
|
||||
vllm serve MODEL \
|
||||
--speculative-config '{"model": "DRAFT_MODEL", "num_speculative_tokens": 5, "method": "draft_model"}'
|
||||
```
|
||||
|
||||
## Advanced topics
|
||||
|
||||
**Server deployment patterns**: See [references/server-deployment.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\serving-llms-vllm/references/server-deployment.md) for Docker, Kubernetes, and load balancing configurations.
|
||||
|
||||
**Performance optimization**: See [references/optimization.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\serving-llms-vllm/references/optimization.md) for PagedAttention tuning, continuous batching details, and benchmark results.
|
||||
|
||||
**Quantization guide**: See [references/quantization.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\serving-llms-vllm/references/quantization.md) for AWQ/GPTQ/FP8 setup, model preparation, and accuracy comparisons.
|
||||
|
||||
**Troubleshooting**: See [references/troubleshooting.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\inference\serving-llms-vllm/references/troubleshooting.md) for detailed error messages, debugging steps, and performance diagnostics.
|
||||
|
||||
## Hardware requirements
|
||||
|
||||
- **Small models (7B-13B)**: 1x A10 (24GB) or A100 (40GB)
|
||||
- **Medium models (30B-40B)**: 2x A100 (40GB) with tensor parallelism
|
||||
- **Large models (70B+)**: 4x A100 (40GB) or 2x A100 (80GB), use AWQ/GPTQ
|
||||
|
||||
Supported platforms: NVIDIA (primary), AMD ROCm, Intel GPUs, TPUs
|
||||
|
||||
## Resources
|
||||
|
||||
- Official docs: https://docs.vllm.ai
|
||||
- GitHub: https://github.com/vllm-project/vllm
|
||||
- Paper: "Efficient Memory Management for Large Language Model Serving with PagedAttention" (SOSP 2023)
|
||||
- Community: https://discuss.vllm.ai
|
||||
@@ -0,0 +1,759 @@
|
||||
---
|
||||
title: "Instructor — Structured LLM outputs validated with Pydantic"
|
||||
sidebar_label: "Instructor"
|
||||
description: "Structured LLM outputs validated with Pydantic"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Instructor
|
||||
|
||||
Structured LLM outputs validated with Pydantic.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/instructor` |
|
||||
| Path | `optional-skills/mlops\instructor` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `instructor`, `pydantic`, `openai`, `anthropic` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Prompt Engineering`, `Instructor`, `Structured Output`, `Pydantic`, `Data Extraction`, `JSON Parsing`, `Type Safety`, `Validation`, `Streaming`, `OpenAI`, `Anthropic` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Instructor: Structured LLM Outputs
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use Instructor when you need to:
|
||||
- **Extract structured data** from LLM responses reliably
|
||||
- **Validate outputs** against Pydantic schemas automatically
|
||||
- **Retry failed extractions** with automatic error handling
|
||||
- **Parse complex JSON** with type safety and validation
|
||||
- **Stream partial results** for real-time processing
|
||||
- **Support multiple LLM providers** with consistent API
|
||||
|
||||
**GitHub Stars**: 15,000+ | **Battle-tested**: 100,000+ developers
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Base installation
|
||||
pip install instructor
|
||||
|
||||
# With specific providers
|
||||
pip install "instructor[anthropic]" # Anthropic Claude
|
||||
pip install "instructor[openai]" # OpenAI
|
||||
pip install "instructor[all]" # All providers
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Basic Example: Extract User Data
|
||||
|
||||
```python
|
||||
import instructor
|
||||
from pydantic import BaseModel
|
||||
from anthropic import Anthropic
|
||||
|
||||
# Define output structure
|
||||
class User(BaseModel):
|
||||
name: str
|
||||
age: int
|
||||
email: str
|
||||
|
||||
# Create instructor client
|
||||
client = instructor.from_anthropic(Anthropic())
|
||||
|
||||
# Extract structured data
|
||||
user = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "John Doe is 30 years old. His email is john@example.com"
|
||||
}],
|
||||
response_model=User
|
||||
)
|
||||
|
||||
print(user.name) # "John Doe"
|
||||
print(user.age) # 30
|
||||
print(user.email) # "john@example.com"
|
||||
```
|
||||
|
||||
### With OpenAI
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = instructor.from_openai(OpenAI())
|
||||
|
||||
user = client.chat.completions.create(
|
||||
model="gpt-4o-mini",
|
||||
response_model=User,
|
||||
messages=[{"role": "user", "content": "Extract: Alice, 25, alice@email.com"}]
|
||||
)
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### 1. Response Models (Pydantic)
|
||||
|
||||
Response models define the structure and validation rules for LLM outputs.
|
||||
|
||||
#### Basic Model
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class Article(BaseModel):
|
||||
title: str = Field(description="Article title")
|
||||
author: str = Field(description="Author name")
|
||||
word_count: int = Field(description="Number of words", gt=0)
|
||||
tags: list[str] = Field(description="List of relevant tags")
|
||||
|
||||
article = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "Analyze this article: [article text]"
|
||||
}],
|
||||
response_model=Article
|
||||
)
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- Type safety with Python type hints
|
||||
- Automatic validation (word_count > 0)
|
||||
- Self-documenting with Field descriptions
|
||||
- IDE autocomplete support
|
||||
|
||||
#### Nested Models
|
||||
|
||||
```python
|
||||
class Address(BaseModel):
|
||||
street: str
|
||||
city: str
|
||||
country: str
|
||||
|
||||
class Person(BaseModel):
|
||||
name: str
|
||||
age: int
|
||||
address: Address # Nested model
|
||||
|
||||
person = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "John lives at 123 Main St, Boston, USA"
|
||||
}],
|
||||
response_model=Person
|
||||
)
|
||||
|
||||
print(person.address.city) # "Boston"
|
||||
```
|
||||
|
||||
#### Optional Fields
|
||||
|
||||
```python
|
||||
from typing import Optional
|
||||
|
||||
class Product(BaseModel):
|
||||
name: str
|
||||
price: float
|
||||
discount: Optional[float] = None # Optional
|
||||
description: str = Field(default="No description") # Default value
|
||||
|
||||
# LLM doesn't need to provide discount or description
|
||||
```
|
||||
|
||||
#### Enums for Constraints
|
||||
|
||||
```python
|
||||
from enum import Enum
|
||||
|
||||
class Sentiment(str, Enum):
|
||||
POSITIVE = "positive"
|
||||
NEGATIVE = "negative"
|
||||
NEUTRAL = "neutral"
|
||||
|
||||
class Review(BaseModel):
|
||||
text: str
|
||||
sentiment: Sentiment # Only these 3 values allowed
|
||||
|
||||
review = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "This product is amazing!"
|
||||
}],
|
||||
response_model=Review
|
||||
)
|
||||
|
||||
print(review.sentiment) # Sentiment.POSITIVE
|
||||
```
|
||||
|
||||
### 2. Validation
|
||||
|
||||
Pydantic validates LLM outputs automatically. If validation fails, Instructor retries.
|
||||
|
||||
#### Built-in Validators
|
||||
|
||||
```python
|
||||
from pydantic import Field, EmailStr, HttpUrl
|
||||
|
||||
class Contact(BaseModel):
|
||||
name: str = Field(min_length=2, max_length=100)
|
||||
age: int = Field(ge=0, le=120) # 0 <= age <= 120
|
||||
email: EmailStr # Validates email format
|
||||
website: HttpUrl # Validates URL format
|
||||
|
||||
# If LLM provides invalid data, Instructor retries automatically
|
||||
```
|
||||
|
||||
#### Custom Validators
|
||||
|
||||
```python
|
||||
from pydantic import field_validator
|
||||
|
||||
class Event(BaseModel):
|
||||
name: str
|
||||
date: str
|
||||
attendees: int
|
||||
|
||||
@field_validator('date')
|
||||
def validate_date(cls, v):
|
||||
"""Ensure date is in YYYY-MM-DD format."""
|
||||
import re
|
||||
if not re.match(r'\d{4}-\d{2}-\d{2}', v):
|
||||
raise ValueError('Date must be YYYY-MM-DD format')
|
||||
return v
|
||||
|
||||
@field_validator('attendees')
|
||||
def validate_attendees(cls, v):
|
||||
"""Ensure positive attendees."""
|
||||
if v < 1:
|
||||
raise ValueError('Must have at least 1 attendee')
|
||||
return v
|
||||
```
|
||||
|
||||
#### Model-Level Validation
|
||||
|
||||
```python
|
||||
from pydantic import model_validator
|
||||
|
||||
class DateRange(BaseModel):
|
||||
start_date: str
|
||||
end_date: str
|
||||
|
||||
@model_validator(mode='after')
|
||||
def check_dates(self):
|
||||
"""Ensure end_date is after start_date."""
|
||||
from datetime import datetime
|
||||
start = datetime.strptime(self.start_date, '%Y-%m-%d')
|
||||
end = datetime.strptime(self.end_date, '%Y-%m-%d')
|
||||
|
||||
if end < start:
|
||||
raise ValueError('end_date must be after start_date')
|
||||
return self
|
||||
```
|
||||
|
||||
### 3. Automatic Retrying
|
||||
|
||||
Instructor retries automatically when validation fails, providing error feedback to the LLM.
|
||||
|
||||
```python
|
||||
# Retries up to 3 times if validation fails
|
||||
user = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "Extract user from: John, age unknown"
|
||||
}],
|
||||
response_model=User,
|
||||
max_retries=3 # Default is 3
|
||||
)
|
||||
|
||||
# If age can't be extracted, Instructor tells the LLM:
|
||||
# "Validation error: age - field required"
|
||||
# LLM tries again with better extraction
|
||||
```
|
||||
|
||||
**How it works:**
|
||||
1. LLM generates output
|
||||
2. Pydantic validates
|
||||
3. If invalid: Error message sent back to LLM
|
||||
4. LLM tries again with error feedback
|
||||
5. Repeats up to max_retries
|
||||
|
||||
### 4. Streaming
|
||||
|
||||
Stream partial results for real-time processing.
|
||||
|
||||
#### Streaming Partial Objects
|
||||
|
||||
```python
|
||||
from instructor import Partial
|
||||
|
||||
class Story(BaseModel):
|
||||
title: str
|
||||
content: str
|
||||
tags: list[str]
|
||||
|
||||
# Stream partial updates as LLM generates
|
||||
for partial_story in client.messages.create_partial(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "Write a short sci-fi story"
|
||||
}],
|
||||
response_model=Story
|
||||
):
|
||||
print(f"Title: {partial_story.title}")
|
||||
print(f"Content so far: {partial_story.content[:100]}...")
|
||||
# Update UI in real-time
|
||||
```
|
||||
|
||||
#### Streaming Iterables
|
||||
|
||||
```python
|
||||
class Task(BaseModel):
|
||||
title: str
|
||||
priority: str
|
||||
|
||||
# Stream list items as they're generated
|
||||
tasks = client.messages.create_iterable(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "Generate 10 project tasks"
|
||||
}],
|
||||
response_model=Task
|
||||
)
|
||||
|
||||
for task in tasks:
|
||||
print(f"- {task.title} ({task.priority})")
|
||||
# Process each task as it arrives
|
||||
```
|
||||
|
||||
## Provider Configuration
|
||||
|
||||
### Anthropic Claude
|
||||
|
||||
```python
|
||||
import instructor
|
||||
from anthropic import Anthropic
|
||||
|
||||
client = instructor.from_anthropic(
|
||||
Anthropic(api_key="your-api-key")
|
||||
)
|
||||
|
||||
# Use with Claude models
|
||||
response = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[...],
|
||||
response_model=YourModel
|
||||
)
|
||||
```
|
||||
|
||||
### OpenAI
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
client = instructor.from_openai(
|
||||
OpenAI(api_key="your-api-key")
|
||||
)
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="gpt-4o-mini",
|
||||
response_model=YourModel,
|
||||
messages=[...]
|
||||
)
|
||||
```
|
||||
|
||||
### Local Models (Ollama)
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
|
||||
# Point to local Ollama server
|
||||
client = instructor.from_openai(
|
||||
OpenAI(
|
||||
base_url="http://localhost:11434/v1",
|
||||
api_key="ollama" # Required but ignored
|
||||
),
|
||||
mode=instructor.Mode.JSON
|
||||
)
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="llama3.1",
|
||||
response_model=YourModel,
|
||||
messages=[...]
|
||||
)
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Pattern 1: Data Extraction from Text
|
||||
|
||||
```python
|
||||
class CompanyInfo(BaseModel):
|
||||
name: str
|
||||
founded_year: int
|
||||
industry: str
|
||||
employees: int
|
||||
headquarters: str
|
||||
|
||||
text = """
|
||||
Tesla, Inc. was founded in 2003. It operates in the automotive and energy
|
||||
industry with approximately 140,000 employees. The company is headquartered
|
||||
in Austin, Texas.
|
||||
"""
|
||||
|
||||
company = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": f"Extract company information from: {text}"
|
||||
}],
|
||||
response_model=CompanyInfo
|
||||
)
|
||||
```
|
||||
|
||||
### Pattern 2: Classification
|
||||
|
||||
```python
|
||||
class Category(str, Enum):
|
||||
TECHNOLOGY = "technology"
|
||||
FINANCE = "finance"
|
||||
HEALTHCARE = "healthcare"
|
||||
EDUCATION = "education"
|
||||
OTHER = "other"
|
||||
|
||||
class ArticleClassification(BaseModel):
|
||||
category: Category
|
||||
confidence: float = Field(ge=0.0, le=1.0)
|
||||
keywords: list[str]
|
||||
|
||||
classification = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": "Classify this article: [article text]"
|
||||
}],
|
||||
response_model=ArticleClassification
|
||||
)
|
||||
```
|
||||
|
||||
### Pattern 3: Multi-Entity Extraction
|
||||
|
||||
```python
|
||||
class Person(BaseModel):
|
||||
name: str
|
||||
role: str
|
||||
|
||||
class Organization(BaseModel):
|
||||
name: str
|
||||
industry: str
|
||||
|
||||
class Entities(BaseModel):
|
||||
people: list[Person]
|
||||
organizations: list[Organization]
|
||||
locations: list[str]
|
||||
|
||||
text = "Tim Cook, CEO of Apple, announced at the event in Cupertino..."
|
||||
|
||||
entities = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": f"Extract all entities from: {text}"
|
||||
}],
|
||||
response_model=Entities
|
||||
)
|
||||
|
||||
for person in entities.people:
|
||||
print(f"{person.name} - {person.role}")
|
||||
```
|
||||
|
||||
### Pattern 4: Structured Analysis
|
||||
|
||||
```python
|
||||
class SentimentAnalysis(BaseModel):
|
||||
overall_sentiment: Sentiment
|
||||
positive_aspects: list[str]
|
||||
negative_aspects: list[str]
|
||||
suggestions: list[str]
|
||||
score: float = Field(ge=-1.0, le=1.0)
|
||||
|
||||
review = "The product works well but setup was confusing..."
|
||||
|
||||
analysis = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": f"Analyze this review: {review}"
|
||||
}],
|
||||
response_model=SentimentAnalysis
|
||||
)
|
||||
```
|
||||
|
||||
### Pattern 5: Batch Processing
|
||||
|
||||
```python
|
||||
def extract_person(text: str) -> Person:
|
||||
return client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": f"Extract person from: {text}"
|
||||
}],
|
||||
response_model=Person
|
||||
)
|
||||
|
||||
texts = [
|
||||
"John Doe is a 30-year-old engineer",
|
||||
"Jane Smith, 25, works in marketing",
|
||||
"Bob Johnson, age 40, software developer"
|
||||
]
|
||||
|
||||
people = [extract_person(text) for text in texts]
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Union Types
|
||||
|
||||
```python
|
||||
from typing import Union
|
||||
|
||||
class TextContent(BaseModel):
|
||||
type: str = "text"
|
||||
content: str
|
||||
|
||||
class ImageContent(BaseModel):
|
||||
type: str = "image"
|
||||
url: HttpUrl
|
||||
caption: str
|
||||
|
||||
class Post(BaseModel):
|
||||
title: str
|
||||
content: Union[TextContent, ImageContent] # Either type
|
||||
|
||||
# LLM chooses appropriate type based on content
|
||||
```
|
||||
|
||||
### Dynamic Models
|
||||
|
||||
```python
|
||||
from pydantic import create_model
|
||||
|
||||
# Create model at runtime
|
||||
DynamicUser = create_model(
|
||||
'User',
|
||||
name=(str, ...),
|
||||
age=(int, Field(ge=0)),
|
||||
email=(EmailStr, ...)
|
||||
)
|
||||
|
||||
user = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[...],
|
||||
response_model=DynamicUser
|
||||
)
|
||||
```
|
||||
|
||||
### Custom Modes
|
||||
|
||||
```python
|
||||
# For providers without native structured outputs
|
||||
client = instructor.from_anthropic(
|
||||
Anthropic(),
|
||||
mode=instructor.Mode.JSON # JSON mode
|
||||
)
|
||||
|
||||
# Available modes:
|
||||
# - Mode.ANTHROPIC_TOOLS (recommended for Claude)
|
||||
# - Mode.JSON (fallback)
|
||||
# - Mode.TOOLS (OpenAI tools)
|
||||
```
|
||||
|
||||
### Context Management
|
||||
|
||||
```python
|
||||
# Single-use client
|
||||
with instructor.from_anthropic(Anthropic()) as client:
|
||||
result = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[...],
|
||||
response_model=YourModel
|
||||
)
|
||||
# Client closed automatically
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Handling Validation Errors
|
||||
|
||||
```python
|
||||
from pydantic import ValidationError
|
||||
|
||||
try:
|
||||
user = client.messages.create(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
max_tokens=1024,
|
||||
messages=[...],
|
||||
response_model=User,
|
||||
max_retries=3
|
||||
)
|
||||
except ValidationError as e:
|
||||
print(f"Failed after retries: {e}")
|
||||
# Handle gracefully
|
||||
|
||||
except Exception as e:
|
||||
print(f"API error: {e}")
|
||||
```
|
||||
|
||||
### Custom Error Messages
|
||||
|
||||
```python
|
||||
class ValidatedUser(BaseModel):
|
||||
name: str = Field(description="Full name, 2-100 characters")
|
||||
age: int = Field(description="Age between 0 and 120", ge=0, le=120)
|
||||
email: EmailStr = Field(description="Valid email address")
|
||||
|
||||
class Config:
|
||||
# Custom error messages
|
||||
json_schema_extra = {
|
||||
"examples": [
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"email": "john@example.com"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Clear Field Descriptions
|
||||
|
||||
```python
|
||||
# ❌ Bad: Vague
|
||||
class Product(BaseModel):
|
||||
name: str
|
||||
price: float
|
||||
|
||||
# ✅ Good: Descriptive
|
||||
class Product(BaseModel):
|
||||
name: str = Field(description="Product name from the text")
|
||||
price: float = Field(description="Price in USD, without currency symbol")
|
||||
```
|
||||
|
||||
### 2. Use Appropriate Validation
|
||||
|
||||
```python
|
||||
# ✅ Good: Constrain values
|
||||
class Rating(BaseModel):
|
||||
score: int = Field(ge=1, le=5, description="Rating from 1 to 5 stars")
|
||||
review: str = Field(min_length=10, description="Review text, at least 10 chars")
|
||||
```
|
||||
|
||||
### 3. Provide Examples in Prompts
|
||||
|
||||
```python
|
||||
messages = [{
|
||||
"role": "user",
|
||||
"content": """Extract person info from: "John, 30, engineer"
|
||||
|
||||
Example format:
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"occupation": "engineer"
|
||||
}"""
|
||||
}]
|
||||
```
|
||||
|
||||
### 4. Use Enums for Fixed Categories
|
||||
|
||||
```python
|
||||
# ✅ Good: Enum ensures valid values
|
||||
class Status(str, Enum):
|
||||
PENDING = "pending"
|
||||
APPROVED = "approved"
|
||||
REJECTED = "rejected"
|
||||
|
||||
class Application(BaseModel):
|
||||
status: Status # LLM must choose from enum
|
||||
```
|
||||
|
||||
### 5. Handle Missing Data Gracefully
|
||||
|
||||
```python
|
||||
class PartialData(BaseModel):
|
||||
required_field: str
|
||||
optional_field: Optional[str] = None
|
||||
default_field: str = "default_value"
|
||||
|
||||
# LLM only needs to provide required_field
|
||||
```
|
||||
|
||||
## Comparison to Alternatives
|
||||
|
||||
| Feature | Instructor | Manual JSON | LangChain | DSPy |
|
||||
|---------|------------|-------------|-----------|------|
|
||||
| Type Safety | ✅ Yes | ❌ No | ⚠️ Partial | ✅ Yes |
|
||||
| Auto Validation | ✅ Yes | ❌ No | ❌ No | ⚠️ Limited |
|
||||
| Auto Retry | ✅ Yes | ❌ No | ❌ No | ✅ Yes |
|
||||
| Streaming | ✅ Yes | ❌ No | ✅ Yes | ❌ No |
|
||||
| Multi-Provider | ✅ Yes | ⚠️ Manual | ✅ Yes | ✅ Yes |
|
||||
| Learning Curve | Low | Low | Medium | High |
|
||||
|
||||
**When to choose Instructor:**
|
||||
- Need structured, validated outputs
|
||||
- Want type safety and IDE support
|
||||
- Require automatic retries
|
||||
- Building data extraction systems
|
||||
|
||||
**When to choose alternatives:**
|
||||
- DSPy: Need prompt optimization
|
||||
- LangChain: Building complex chains
|
||||
- Manual: Simple, one-off extractions
|
||||
|
||||
## Resources
|
||||
|
||||
- **Documentation**: https://python.useinstructor.com
|
||||
- **GitHub**: https://github.com/jxnl/instructor (15k+ stars)
|
||||
- **Cookbook**: https://python.useinstructor.com/examples
|
||||
- **Discord**: Community support available
|
||||
|
||||
## See Also
|
||||
|
||||
- `references/validation.md` - Advanced validation patterns
|
||||
- `references/providers.md` - Provider-specific configuration
|
||||
- `references/examples.md` - Real-world use cases
|
||||
@@ -0,0 +1,568 @@
|
||||
---
|
||||
title: "Lambda Labs — On-demand GPU cloud instances for ML training"
|
||||
sidebar_label: "Lambda Labs"
|
||||
description: "On-demand GPU cloud instances for ML training"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Lambda Labs
|
||||
|
||||
On-demand GPU cloud instances for ML training.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/lambda-labs` |
|
||||
| Path | `optional-skills/mlops\lambda-labs` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `lambda-cloud-client>=1.0.0` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Infrastructure`, `GPU Cloud`, `Training`, `Inference`, `Lambda Labs` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Lambda Labs GPU Cloud
|
||||
|
||||
Guide to running ML workloads on Lambda Labs GPU cloud with on-demand instances and 1-Click Clusters.
|
||||
|
||||
## When to use Lambda Labs
|
||||
|
||||
**Use Lambda Labs when:**
|
||||
- Need dedicated GPU instances with full SSH access
|
||||
- Running long training jobs (hours to days)
|
||||
- Want simple pricing with no egress fees
|
||||
- Need persistent storage across sessions
|
||||
- Require high-performance multi-node clusters (16-512 GPUs)
|
||||
- Want pre-installed ML stack (Lambda Stack with PyTorch, CUDA, NCCL)
|
||||
|
||||
**Key features:**
|
||||
- **GPU variety**: B200, H100, GH200, A100, A10, A6000, V100
|
||||
- **Lambda Stack**: Pre-installed PyTorch, TensorFlow, CUDA, cuDNN, NCCL
|
||||
- **Persistent filesystems**: Keep data across instance restarts
|
||||
- **1-Click Clusters**: 16-512 GPU Slurm clusters with InfiniBand
|
||||
- **Simple pricing**: Pay-per-minute, no egress fees
|
||||
- **Global regions**: 12+ regions worldwide
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **Modal**: For serverless, auto-scaling workloads
|
||||
- **SkyPilot**: For multi-cloud orchestration and cost optimization
|
||||
- **RunPod**: For cheaper spot instances and serverless endpoints
|
||||
- **Vast.ai**: For GPU marketplace with lowest prices
|
||||
|
||||
## Quick start
|
||||
|
||||
### Account setup
|
||||
|
||||
1. Create account at https://lambda.ai
|
||||
2. Add payment method
|
||||
3. Generate API key from dashboard
|
||||
4. Add SSH key (required before launching instances)
|
||||
|
||||
### Launch via console
|
||||
|
||||
1. Go to https://cloud.lambda.ai/instances
|
||||
2. Click "Launch instance"
|
||||
3. Select GPU type and region
|
||||
4. Choose SSH key
|
||||
5. Optionally attach filesystem
|
||||
6. Launch and wait 3-15 minutes
|
||||
|
||||
### Connect via SSH
|
||||
|
||||
```bash
|
||||
# Get instance IP from console
|
||||
ssh ubuntu@<INSTANCE-IP>
|
||||
|
||||
# Or with specific key
|
||||
ssh -i ~/.ssh/lambda_key ubuntu@<INSTANCE-IP>
|
||||
```
|
||||
|
||||
## GPU instances
|
||||
|
||||
### Available GPUs
|
||||
|
||||
| GPU | VRAM | Price/GPU/hr | Best For |
|
||||
|-----|------|--------------|----------|
|
||||
| B200 SXM6 | 180 GB | $4.99 | Largest models, fastest training |
|
||||
| H100 SXM | 80 GB | $2.99-3.29 | Large model training |
|
||||
| H100 PCIe | 80 GB | $2.49 | Cost-effective H100 |
|
||||
| GH200 | 96 GB | $1.49 | Single-GPU large models |
|
||||
| A100 80GB | 80 GB | $1.79 | Production training |
|
||||
| A100 40GB | 40 GB | $1.29 | Standard training |
|
||||
| A10 | 24 GB | $0.75 | Inference, fine-tuning |
|
||||
| A6000 | 48 GB | $0.80 | Good VRAM/price ratio |
|
||||
| V100 | 16 GB | $0.55 | Budget training |
|
||||
|
||||
### Instance configurations
|
||||
|
||||
```
|
||||
8x GPU: Best for distributed training (DDP, FSDP)
|
||||
4x GPU: Large models, multi-GPU training
|
||||
2x GPU: Medium workloads
|
||||
1x GPU: Fine-tuning, inference, development
|
||||
```
|
||||
|
||||
### Launch times
|
||||
|
||||
- Single-GPU: 3-5 minutes
|
||||
- Multi-GPU: 10-15 minutes
|
||||
|
||||
## Lambda Stack
|
||||
|
||||
All instances come with Lambda Stack pre-installed:
|
||||
|
||||
```bash
|
||||
# Included software
|
||||
- Ubuntu 22.04 LTS
|
||||
- NVIDIA drivers (latest)
|
||||
- CUDA 12.x
|
||||
- cuDNN 8.x
|
||||
- NCCL (for multi-GPU)
|
||||
- PyTorch (latest)
|
||||
- TensorFlow (latest)
|
||||
- JAX
|
||||
- JupyterLab
|
||||
```
|
||||
|
||||
### Verify installation
|
||||
|
||||
```bash
|
||||
# Check GPU
|
||||
nvidia-smi
|
||||
|
||||
# Check PyTorch
|
||||
python -c "import torch; print(torch.cuda.is_available())"
|
||||
|
||||
# Check CUDA version
|
||||
nvcc --version
|
||||
```
|
||||
|
||||
## Python API
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
pip install lambda-cloud-client
|
||||
```
|
||||
|
||||
### Authentication
|
||||
|
||||
```python
|
||||
import os
|
||||
import lambda_cloud_client
|
||||
|
||||
# Configure with API key
|
||||
configuration = lambda_cloud_client.Configuration(
|
||||
host="https://cloud.lambdalabs.com/api/v1",
|
||||
access_token=os.environ["LAMBDA_API_KEY"]
|
||||
)
|
||||
```
|
||||
|
||||
### List available instances
|
||||
|
||||
```python
|
||||
with lambda_cloud_client.ApiClient(configuration) as api_client:
|
||||
api = lambda_cloud_client.DefaultApi(api_client)
|
||||
|
||||
# Get available instance types
|
||||
types = api.instance_types()
|
||||
for name, info in types.data.items():
|
||||
print(f"{name}: {info.instance_type.description}")
|
||||
```
|
||||
|
||||
### Launch instance
|
||||
|
||||
```python
|
||||
from lambda_cloud_client.models import LaunchInstanceRequest
|
||||
|
||||
request = LaunchInstanceRequest(
|
||||
region_name="us-west-1",
|
||||
instance_type_name="gpu_1x_h100_sxm5",
|
||||
ssh_key_names=["my-ssh-key"],
|
||||
file_system_names=["my-filesystem"], # Optional
|
||||
name="training-job"
|
||||
)
|
||||
|
||||
response = api.launch_instance(request)
|
||||
instance_id = response.data.instance_ids[0]
|
||||
print(f"Launched: {instance_id}")
|
||||
```
|
||||
|
||||
### List running instances
|
||||
|
||||
```python
|
||||
instances = api.list_instances()
|
||||
for instance in instances.data:
|
||||
print(f"{instance.name}: {instance.ip} ({instance.status})")
|
||||
```
|
||||
|
||||
### Terminate instance
|
||||
|
||||
```python
|
||||
from lambda_cloud_client.models import TerminateInstanceRequest
|
||||
|
||||
request = TerminateInstanceRequest(
|
||||
instance_ids=[instance_id]
|
||||
)
|
||||
api.terminate_instance(request)
|
||||
```
|
||||
|
||||
### SSH key management
|
||||
|
||||
```python
|
||||
from lambda_cloud_client.models import AddSshKeyRequest
|
||||
|
||||
# Add SSH key
|
||||
request = AddSshKeyRequest(
|
||||
name="my-key",
|
||||
public_key="ssh-rsa AAAA..."
|
||||
)
|
||||
api.add_ssh_key(request)
|
||||
|
||||
# List keys
|
||||
keys = api.list_ssh_keys()
|
||||
|
||||
# Delete key
|
||||
api.delete_ssh_key(key_id)
|
||||
```
|
||||
|
||||
## CLI with curl
|
||||
|
||||
### List instance types
|
||||
|
||||
```bash
|
||||
curl -u $LAMBDA_API_KEY: \
|
||||
https://cloud.lambdalabs.com/api/v1/instance-types | jq
|
||||
```
|
||||
|
||||
### Launch instance
|
||||
|
||||
```bash
|
||||
curl -u $LAMBDA_API_KEY: \
|
||||
-X POST https://cloud.lambdalabs.com/api/v1/instance-operations/launch \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"region_name": "us-west-1",
|
||||
"instance_type_name": "gpu_1x_h100_sxm5",
|
||||
"ssh_key_names": ["my-key"]
|
||||
}' | jq
|
||||
```
|
||||
|
||||
### Terminate instance
|
||||
|
||||
```bash
|
||||
curl -u $LAMBDA_API_KEY: \
|
||||
-X POST https://cloud.lambdalabs.com/api/v1/instance-operations/terminate \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"instance_ids": ["<INSTANCE-ID>"]}' | jq
|
||||
```
|
||||
|
||||
## Persistent storage
|
||||
|
||||
### Filesystems
|
||||
|
||||
Filesystems persist data across instance restarts:
|
||||
|
||||
```bash
|
||||
# Mount location
|
||||
/lambda/nfs/<FILESYSTEM_NAME>
|
||||
|
||||
# Example: save checkpoints
|
||||
python train.py --checkpoint-dir /lambda/nfs/my-storage/checkpoints
|
||||
```
|
||||
|
||||
### Create filesystem
|
||||
|
||||
1. Go to Storage in Lambda console
|
||||
2. Click "Create filesystem"
|
||||
3. Select region (must match instance region)
|
||||
4. Name and create
|
||||
|
||||
### Attach to instance
|
||||
|
||||
Filesystems must be attached at instance launch time:
|
||||
- Via console: Select filesystem when launching
|
||||
- Via API: Include `file_system_names` in launch request
|
||||
|
||||
### Best practices
|
||||
|
||||
<!-- ascii-guard-ignore -->
|
||||
```bash
|
||||
# Store on filesystem (persists)
|
||||
/lambda/nfs/storage/
|
||||
├── datasets/
|
||||
├── checkpoints/
|
||||
├── models/
|
||||
└── outputs/
|
||||
|
||||
# Local SSD (faster, ephemeral)
|
||||
~/ (instance home)
|
||||
└── working/ # Temporary files
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
## SSH configuration
|
||||
|
||||
### Add SSH key
|
||||
|
||||
```bash
|
||||
# Generate key locally
|
||||
ssh-keygen -t ed25519 -f ~/.ssh/lambda_key
|
||||
|
||||
# Add public key to Lambda console
|
||||
# Or via API
|
||||
```
|
||||
|
||||
### Multiple keys
|
||||
|
||||
```bash
|
||||
# On instance, add more keys
|
||||
echo 'ssh-rsa AAAA...' >> ~/.ssh/authorized_keys
|
||||
```
|
||||
|
||||
### Import from GitHub
|
||||
|
||||
```bash
|
||||
# On instance
|
||||
ssh-import-id gh:username
|
||||
```
|
||||
|
||||
### SSH tunneling
|
||||
|
||||
```bash
|
||||
# Forward Jupyter
|
||||
ssh -L 8888:localhost:8888 ubuntu@<IP>
|
||||
|
||||
# Forward TensorBoard
|
||||
ssh -L 6006:localhost:6006 ubuntu@<IP>
|
||||
|
||||
# Multiple ports
|
||||
ssh -L 8888:localhost:8888 -L 6006:localhost:6006 ubuntu@<IP>
|
||||
```
|
||||
|
||||
## JupyterLab
|
||||
|
||||
### Launch from console
|
||||
|
||||
1. Go to Instances page
|
||||
2. Click "Launch" in Cloud IDE column
|
||||
3. JupyterLab opens in browser
|
||||
|
||||
### Manual access
|
||||
|
||||
```bash
|
||||
# On instance
|
||||
jupyter lab --ip=0.0.0.0 --port=8888
|
||||
|
||||
# From local machine with tunnel
|
||||
ssh -L 8888:localhost:8888 ubuntu@<IP>
|
||||
# Open http://localhost:8888
|
||||
```
|
||||
|
||||
## Training workflows
|
||||
|
||||
### Single-GPU training
|
||||
|
||||
```bash
|
||||
# SSH to instance
|
||||
ssh ubuntu@<IP>
|
||||
|
||||
# Clone repo
|
||||
git clone https://github.com/user/project
|
||||
cd project
|
||||
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Train
|
||||
python train.py --epochs 100 --checkpoint-dir /lambda/nfs/storage/checkpoints
|
||||
```
|
||||
|
||||
### Multi-GPU training (single node)
|
||||
|
||||
```python
|
||||
# train_ddp.py
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
|
||||
def main():
|
||||
dist.init_process_group("nccl")
|
||||
rank = dist.get_rank()
|
||||
device = rank % torch.cuda.device_count()
|
||||
|
||||
model = MyModel().to(device)
|
||||
model = DDP(model, device_ids=[device])
|
||||
|
||||
# Training loop...
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
```bash
|
||||
# Launch with torchrun (8 GPUs)
|
||||
torchrun --nproc_per_node=8 train_ddp.py
|
||||
```
|
||||
|
||||
### Checkpoint to filesystem
|
||||
|
||||
```python
|
||||
import os
|
||||
|
||||
checkpoint_dir = "/lambda/nfs/my-storage/checkpoints"
|
||||
os.makedirs(checkpoint_dir, exist_ok=True)
|
||||
|
||||
# Save checkpoint
|
||||
torch.save({
|
||||
'epoch': epoch,
|
||||
'model_state_dict': model.state_dict(),
|
||||
'optimizer_state_dict': optimizer.state_dict(),
|
||||
'loss': loss,
|
||||
}, f"{checkpoint_dir}/checkpoint_{epoch}.pt")
|
||||
```
|
||||
|
||||
## 1-Click Clusters
|
||||
|
||||
### Overview
|
||||
|
||||
High-performance Slurm clusters with:
|
||||
- 16-512 NVIDIA H100 or B200 GPUs
|
||||
- NVIDIA Quantum-2 400 Gb/s InfiniBand
|
||||
- GPUDirect RDMA at 3200 Gb/s
|
||||
- Pre-installed distributed ML stack
|
||||
|
||||
### Included software
|
||||
|
||||
- Ubuntu 22.04 LTS + Lambda Stack
|
||||
- NCCL, Open MPI
|
||||
- PyTorch with DDP and FSDP
|
||||
- TensorFlow
|
||||
- OFED drivers
|
||||
|
||||
### Storage
|
||||
|
||||
- 24 TB NVMe per compute node (ephemeral)
|
||||
- Lambda filesystems for persistent data
|
||||
|
||||
### Multi-node training
|
||||
|
||||
```bash
|
||||
# On Slurm cluster
|
||||
srun --nodes=4 --ntasks-per-node=8 --gpus-per-node=8 \
|
||||
torchrun --nnodes=4 --nproc_per_node=8 \
|
||||
--rdzv_backend=c10d --rdzv_endpoint=$MASTER_ADDR:29500 \
|
||||
train.py
|
||||
```
|
||||
|
||||
## Networking
|
||||
|
||||
### Bandwidth
|
||||
|
||||
- Inter-instance (same region): up to 200 Gbps
|
||||
- Internet outbound: 20 Gbps max
|
||||
|
||||
### Firewall
|
||||
|
||||
- Default: Only port 22 (SSH) open
|
||||
- Configure additional ports in Lambda console
|
||||
- ICMP traffic allowed by default
|
||||
|
||||
### Private IPs
|
||||
|
||||
```bash
|
||||
# Find private IP
|
||||
ip addr show | grep 'inet '
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: Fine-tuning LLM
|
||||
|
||||
```bash
|
||||
# 1. Launch 8x H100 instance with filesystem
|
||||
|
||||
# 2. SSH and setup
|
||||
ssh ubuntu@<IP>
|
||||
pip install transformers accelerate peft
|
||||
|
||||
# 3. Download model to filesystem
|
||||
python -c "
|
||||
from transformers import AutoModelForCausalLM
|
||||
model = AutoModelForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf')
|
||||
model.save_pretrained('/lambda/nfs/storage/models/llama-2-7b')
|
||||
"
|
||||
|
||||
# 4. Fine-tune with checkpoints on filesystem
|
||||
accelerate launch --num_processes 8 train.py \
|
||||
--model_path /lambda/nfs/storage/models/llama-2-7b \
|
||||
--output_dir /lambda/nfs/storage/outputs \
|
||||
--checkpoint_dir /lambda/nfs/storage/checkpoints
|
||||
```
|
||||
|
||||
### Workflow 2: Batch inference
|
||||
|
||||
```bash
|
||||
# 1. Launch A10 instance (cost-effective for inference)
|
||||
|
||||
# 2. Run inference
|
||||
python inference.py \
|
||||
--model /lambda/nfs/storage/models/fine-tuned \
|
||||
--input /lambda/nfs/storage/data/inputs.jsonl \
|
||||
--output /lambda/nfs/storage/data/outputs.jsonl
|
||||
```
|
||||
|
||||
## Cost optimization
|
||||
|
||||
### Choose right GPU
|
||||
|
||||
| Task | Recommended GPU |
|
||||
|------|-----------------|
|
||||
| LLM fine-tuning (7B) | A100 40GB |
|
||||
| LLM fine-tuning (70B) | 8x H100 |
|
||||
| Inference | A10, A6000 |
|
||||
| Development | V100, A10 |
|
||||
| Maximum performance | B200 |
|
||||
|
||||
### Reduce costs
|
||||
|
||||
1. **Use filesystems**: Avoid re-downloading data
|
||||
2. **Checkpoint frequently**: Resume interrupted training
|
||||
3. **Right-size**: Don't over-provision GPUs
|
||||
4. **Terminate idle**: No auto-stop, manually terminate
|
||||
|
||||
### Monitor usage
|
||||
|
||||
- Dashboard shows real-time GPU utilization
|
||||
- API for programmatic monitoring
|
||||
|
||||
## Common issues
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Instance won't launch | Check region availability, try different GPU |
|
||||
| SSH connection refused | Wait for instance to initialize (3-15 min) |
|
||||
| Data lost after terminate | Use persistent filesystems |
|
||||
| Slow data transfer | Use filesystem in same region |
|
||||
| GPU not detected | Reboot instance, check drivers |
|
||||
|
||||
## References
|
||||
|
||||
- **[Advanced Usage](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\lambda-labs/references/advanced-usage.md)** - Multi-node training, API automation
|
||||
- **[Troubleshooting](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\lambda-labs/references/troubleshooting.md)** - Common issues and solutions
|
||||
|
||||
## Resources
|
||||
|
||||
- **Documentation**: https://docs.lambda.ai
|
||||
- **Console**: https://cloud.lambda.ai
|
||||
- **Pricing**: https://lambda.ai/instances
|
||||
- **Support**: https://support.lambdalabs.com
|
||||
- **Blog**: https://lambda.ai/blog
|
||||
@@ -0,0 +1,323 @@
|
||||
---
|
||||
title: "Llava — Vision-language chat: VQA, captioning, image dialogue"
|
||||
sidebar_label: "Llava"
|
||||
description: "Vision-language chat: VQA, captioning, image dialogue"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Llava
|
||||
|
||||
Vision-language chat: VQA, captioning, image dialogue.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/llava` |
|
||||
| Path | `optional-skills/mlops\llava` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `transformers`, `torch`, `pillow` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `LLaVA`, `Vision-Language`, `Multimodal`, `Visual Question Answering`, `Image Chat`, `CLIP`, `Vicuna`, `Conversational AI`, `Instruction Tuning`, `VQA` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# LLaVA - Large Language and Vision Assistant
|
||||
|
||||
Open-source vision-language model for conversational image understanding.
|
||||
|
||||
## When to use LLaVA
|
||||
|
||||
**Use when:**
|
||||
- Building vision-language chatbots
|
||||
- Visual question answering (VQA)
|
||||
- Image description and captioning
|
||||
- Multi-turn image conversations
|
||||
- Visual instruction following
|
||||
- Document understanding with images
|
||||
|
||||
**Metrics**:
|
||||
- **23,000+ GitHub stars**
|
||||
- GPT-4V level capabilities (targeted)
|
||||
- Apache 2.0 License
|
||||
- Multiple model sizes (7B-34B params)
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **GPT-4V**: Highest quality, API-based
|
||||
- **CLIP**: Simple zero-shot classification
|
||||
- **BLIP-2**: Better for captioning only
|
||||
- **Flamingo**: Research, not open-source
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Clone repository
|
||||
git clone https://github.com/haotian-liu/LLaVA
|
||||
cd LLaVA
|
||||
|
||||
# Install
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
### Basic usage
|
||||
|
||||
```python
|
||||
from llava.model.builder import load_pretrained_model
|
||||
from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token
|
||||
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
|
||||
from llava.conversation import conv_templates
|
||||
from PIL import Image
|
||||
import torch
|
||||
|
||||
# Load model
|
||||
model_path = "liuhaotian/llava-v1.5-7b"
|
||||
tokenizer, model, image_processor, context_len = load_pretrained_model(
|
||||
model_path=model_path,
|
||||
model_base=None,
|
||||
model_name=get_model_name_from_path(model_path)
|
||||
)
|
||||
|
||||
# Load image
|
||||
image = Image.open("image.jpg")
|
||||
image_tensor = process_images([image], image_processor, model.config)
|
||||
image_tensor = image_tensor.to(model.device, dtype=torch.float16)
|
||||
|
||||
# Create conversation
|
||||
conv = conv_templates["llava_v1"].copy()
|
||||
conv.append_message(conv.roles[0], DEFAULT_IMAGE_TOKEN + "\nWhat is in this image?")
|
||||
conv.append_message(conv.roles[1], None)
|
||||
prompt = conv.get_prompt()
|
||||
|
||||
# Generate response
|
||||
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device)
|
||||
|
||||
with torch.inference_mode():
|
||||
output_ids = model.generate(
|
||||
input_ids,
|
||||
images=image_tensor,
|
||||
do_sample=True,
|
||||
temperature=0.2,
|
||||
max_new_tokens=512
|
||||
)
|
||||
|
||||
response = tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
|
||||
print(response)
|
||||
```
|
||||
|
||||
## Available models
|
||||
|
||||
| Model | Parameters | VRAM | Quality |
|
||||
|-------|------------|------|---------|
|
||||
| LLaVA-v1.5-7B | 7B | ~14 GB | Good |
|
||||
| LLaVA-v1.5-13B | 13B | ~28 GB | Better |
|
||||
| LLaVA-v1.6-34B | 34B | ~70 GB | Best |
|
||||
|
||||
```python
|
||||
# Load different models
|
||||
model_7b = "liuhaotian/llava-v1.5-7b"
|
||||
model_13b = "liuhaotian/llava-v1.5-13b"
|
||||
model_34b = "liuhaotian/llava-v1.6-34b"
|
||||
|
||||
# 4-bit quantization for lower VRAM
|
||||
load_4bit = True # Reduces VRAM by ~4×
|
||||
```
|
||||
|
||||
## CLI usage
|
||||
|
||||
```bash
|
||||
# Single image query
|
||||
python -m llava.serve.cli \
|
||||
--model-path liuhaotian/llava-v1.5-7b \
|
||||
--image-file image.jpg \
|
||||
--query "What is in this image?"
|
||||
|
||||
# Multi-turn conversation
|
||||
python -m llava.serve.cli \
|
||||
--model-path liuhaotian/llava-v1.5-7b \
|
||||
--image-file image.jpg
|
||||
# Then type questions interactively
|
||||
```
|
||||
|
||||
## Web UI (Gradio)
|
||||
|
||||
```bash
|
||||
# Launch Gradio interface
|
||||
python -m llava.serve.gradio_web_server \
|
||||
--model-path liuhaotian/llava-v1.5-7b \
|
||||
--load-4bit # Optional: reduce VRAM
|
||||
|
||||
# Access at http://localhost:7860
|
||||
```
|
||||
|
||||
## Multi-turn conversations
|
||||
|
||||
```python
|
||||
# Initialize conversation
|
||||
conv = conv_templates["llava_v1"].copy()
|
||||
|
||||
# Turn 1
|
||||
conv.append_message(conv.roles[0], DEFAULT_IMAGE_TOKEN + "\nWhat is in this image?")
|
||||
conv.append_message(conv.roles[1], None)
|
||||
response1 = generate(conv, model, image) # "A dog playing in a park"
|
||||
|
||||
# Turn 2
|
||||
conv.messages[-1][1] = response1 # Add previous response
|
||||
conv.append_message(conv.roles[0], "What breed is the dog?")
|
||||
conv.append_message(conv.roles[1], None)
|
||||
response2 = generate(conv, model, image) # "Golden Retriever"
|
||||
|
||||
# Turn 3
|
||||
conv.messages[-1][1] = response2
|
||||
conv.append_message(conv.roles[0], "What time of day is it?")
|
||||
conv.append_message(conv.roles[1], None)
|
||||
response3 = generate(conv, model, image)
|
||||
```
|
||||
|
||||
## Common tasks
|
||||
|
||||
### Image captioning
|
||||
|
||||
```python
|
||||
question = "Describe this image in detail."
|
||||
response = ask(model, image, question)
|
||||
```
|
||||
|
||||
### Visual question answering
|
||||
|
||||
```python
|
||||
question = "How many people are in the image?"
|
||||
response = ask(model, image, question)
|
||||
```
|
||||
|
||||
### Object detection (textual)
|
||||
|
||||
```python
|
||||
question = "List all the objects you can see in this image."
|
||||
response = ask(model, image, question)
|
||||
```
|
||||
|
||||
### Scene understanding
|
||||
|
||||
```python
|
||||
question = "What is happening in this scene?"
|
||||
response = ask(model, image, question)
|
||||
```
|
||||
|
||||
### Document understanding
|
||||
|
||||
```python
|
||||
question = "What is the main topic of this document?"
|
||||
response = ask(model, document_image, question)
|
||||
```
|
||||
|
||||
## Training custom model
|
||||
|
||||
```bash
|
||||
# Stage 1: Feature alignment (558K image-caption pairs)
|
||||
bash scripts/v1_5/pretrain.sh
|
||||
|
||||
# Stage 2: Visual instruction tuning (150K instruction data)
|
||||
bash scripts/v1_5/finetune.sh
|
||||
```
|
||||
|
||||
## Quantization (reduce VRAM)
|
||||
|
||||
```python
|
||||
# 4-bit quantization
|
||||
tokenizer, model, image_processor, context_len = load_pretrained_model(
|
||||
model_path="liuhaotian/llava-v1.5-13b",
|
||||
model_base=None,
|
||||
model_name=get_model_name_from_path("liuhaotian/llava-v1.5-13b"),
|
||||
load_4bit=True # Reduces VRAM ~4×
|
||||
)
|
||||
|
||||
# 8-bit quantization
|
||||
load_8bit=True # Reduces VRAM ~2×
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
1. **Start with 7B model** - Good quality, manageable VRAM
|
||||
2. **Use 4-bit quantization** - Reduces VRAM significantly
|
||||
3. **GPU required** - CPU inference extremely slow
|
||||
4. **Clear prompts** - Specific questions get better answers
|
||||
5. **Multi-turn conversations** - Maintain conversation context
|
||||
6. **Temperature 0.2-0.7** - Balance creativity/consistency
|
||||
7. **max_new_tokens 512-1024** - For detailed responses
|
||||
8. **Batch processing** - Process multiple images sequentially
|
||||
|
||||
## Performance
|
||||
|
||||
| Model | VRAM (FP16) | VRAM (4-bit) | Speed (tokens/s) |
|
||||
|-------|-------------|--------------|------------------|
|
||||
| 7B | ~14 GB | ~4 GB | ~20 |
|
||||
| 13B | ~28 GB | ~8 GB | ~12 |
|
||||
| 34B | ~70 GB | ~18 GB | ~5 |
|
||||
|
||||
*On A100 GPU*
|
||||
|
||||
## Benchmarks
|
||||
|
||||
LLaVA achieves competitive scores on:
|
||||
- **VQAv2**: 78.5%
|
||||
- **GQA**: 62.0%
|
||||
- **MM-Vet**: 35.4%
|
||||
- **MMBench**: 64.3%
|
||||
|
||||
## Limitations
|
||||
|
||||
1. **Hallucinations** - May describe things not in image
|
||||
2. **Spatial reasoning** - Struggles with precise locations
|
||||
3. **Small text** - Difficulty reading fine print
|
||||
4. **Object counting** - Imprecise for many objects
|
||||
5. **VRAM requirements** - Need powerful GPU
|
||||
6. **Inference speed** - Slower than CLIP
|
||||
|
||||
## Integration with frameworks
|
||||
|
||||
### LangChain
|
||||
|
||||
```python
|
||||
from langchain.llms.base import LLM
|
||||
|
||||
class LLaVALLM(LLM):
|
||||
def _call(self, prompt, stop=None):
|
||||
# Custom LLaVA inference
|
||||
return response
|
||||
|
||||
llm = LLaVALLM()
|
||||
```
|
||||
|
||||
### Gradio App
|
||||
|
||||
```python
|
||||
import gradio as gr
|
||||
|
||||
def chat(image, text, history):
|
||||
response = ask_llava(model, image, text)
|
||||
return response
|
||||
|
||||
demo = gr.ChatInterface(
|
||||
chat,
|
||||
additional_inputs=[gr.Image(type="pil")],
|
||||
title="LLaVA Chat"
|
||||
)
|
||||
demo.launch()
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/haotian-liu/LLaVA ⭐ 23,000+
|
||||
- **Paper**: https://arxiv.org/abs/2304.08485
|
||||
- **Demo**: https://llava.hliu.cc
|
||||
- **Models**: https://huggingface.co/liuhaotian
|
||||
- **License**: Apache 2.0
|
||||
@@ -0,0 +1,368 @@
|
||||
---
|
||||
title: "Modal — Serverless GPU cloud for ML jobs and model APIs"
|
||||
sidebar_label: "Modal"
|
||||
description: "Serverless GPU cloud for ML jobs and model APIs"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Modal
|
||||
|
||||
Serverless GPU cloud for ML jobs and model APIs.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/modal` |
|
||||
| Path | `optional-skills/mlops\modal` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `modal>=1.0` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Infrastructure`, `Serverless`, `GPU`, `Cloud`, `Deployment`, `Modal` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Modal Serverless GPU
|
||||
|
||||
Guide to running ML workloads on Modal's serverless GPU cloud platform.
|
||||
|
||||
## When to use Modal
|
||||
|
||||
**Use Modal when:**
|
||||
- Running GPU-intensive ML workloads without managing infrastructure
|
||||
- Deploying ML models as auto-scaling APIs
|
||||
- Running batch processing jobs (training, inference, data processing)
|
||||
- Need pay-per-second GPU pricing without idle costs
|
||||
- Prototyping ML applications quickly
|
||||
- Running scheduled jobs (cron-like workloads)
|
||||
|
||||
**Key features:**
|
||||
- **Serverless GPUs**: T4, L4, A10G, L40S, A100, H100, H200, B200 on-demand
|
||||
- **Python-native**: Define infrastructure in Python code, no YAML
|
||||
- **Auto-scaling**: Scale to zero, scale to 100+ GPUs instantly
|
||||
- **Sub-second cold starts**: Rust-based infrastructure for fast container launches
|
||||
- **Container caching**: Image layers cached for rapid iteration
|
||||
- **Web endpoints**: Deploy functions as REST APIs with zero-downtime updates
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **RunPod**: For longer-running pods with persistent state
|
||||
- **Lambda Labs**: For reserved GPU instances
|
||||
- **SkyPilot**: For multi-cloud orchestration and cost optimization
|
||||
- **Kubernetes**: For complex multi-service architectures
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
pip install modal
|
||||
modal setup # Opens browser for authentication
|
||||
```
|
||||
|
||||
### Hello World with GPU
|
||||
|
||||
```python
|
||||
import modal
|
||||
|
||||
app = modal.App("hello-gpu")
|
||||
|
||||
@app.function(gpu="T4")
|
||||
def gpu_info():
|
||||
import subprocess
|
||||
return subprocess.run(["nvidia-smi"], capture_output=True, text=True).stdout
|
||||
|
||||
@app.local_entrypoint()
|
||||
def main():
|
||||
print(gpu_info.remote())
|
||||
```
|
||||
|
||||
Run: `modal run hello_gpu.py`
|
||||
|
||||
### Basic inference endpoint
|
||||
|
||||
```python
|
||||
import modal
|
||||
|
||||
app = modal.App("text-generation")
|
||||
image = modal.Image.debian_slim().pip_install("transformers", "torch", "accelerate")
|
||||
|
||||
@app.cls(gpu="A10G", image=image)
|
||||
class TextGenerator:
|
||||
@modal.enter()
|
||||
def load_model(self):
|
||||
from transformers import pipeline
|
||||
self.pipe = pipeline("text-generation", model="gpt2", device=0)
|
||||
|
||||
@modal.method()
|
||||
def generate(self, prompt: str) -> str:
|
||||
return self.pipe(prompt, max_length=100)[0]["generated_text"]
|
||||
|
||||
@app.local_entrypoint()
|
||||
def main():
|
||||
print(TextGenerator().generate.remote("Hello, world"))
|
||||
```
|
||||
|
||||
## Core concepts
|
||||
|
||||
### Key components
|
||||
|
||||
| Component | Purpose |
|
||||
|-----------|---------|
|
||||
| `App` | Container for functions and resources |
|
||||
| `Function` | Serverless function with compute specs |
|
||||
| `Cls` | Class-based functions with lifecycle hooks |
|
||||
| `Image` | Container image definition |
|
||||
| `Volume` | Persistent storage for models/data |
|
||||
| `Secret` | Secure credential storage |
|
||||
|
||||
### Execution modes
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `modal run script.py` | Execute and exit |
|
||||
| `modal serve script.py` | Development with live reload |
|
||||
| `modal deploy script.py` | Persistent cloud deployment |
|
||||
|
||||
## GPU configuration
|
||||
|
||||
### Available GPUs
|
||||
|
||||
| GPU | VRAM | Best For |
|
||||
|-----|------|----------|
|
||||
| `T4` | 16GB | Budget inference, small models |
|
||||
| `L4` | 24GB | Inference, Ada Lovelace arch |
|
||||
| `A10G` | 24GB | Training/inference, 3.3x faster than T4 |
|
||||
| `L40S` | 48GB | Recommended for inference (best cost/perf) |
|
||||
| `A100-40GB` | 40GB | Large model training |
|
||||
| `A100-80GB` | 80GB | Very large models |
|
||||
| `H100` | 80GB | Fastest, FP8 + Transformer Engine |
|
||||
| `H200` | 141GB | Auto-upgrade from H100, 4.8TB/s bandwidth |
|
||||
| `B200` | Latest | Blackwell architecture |
|
||||
|
||||
### GPU specification patterns
|
||||
|
||||
```python
|
||||
# Single GPU
|
||||
@app.function(gpu="A100")
|
||||
|
||||
# Specific memory variant
|
||||
@app.function(gpu="A100-80GB")
|
||||
|
||||
# Multiple GPUs (up to 8)
|
||||
@app.function(gpu="H100:4")
|
||||
|
||||
# GPU with fallbacks
|
||||
@app.function(gpu=["H100", "A100", "L40S"])
|
||||
|
||||
# Any available GPU
|
||||
@app.function(gpu="any")
|
||||
```
|
||||
|
||||
## Container images
|
||||
|
||||
```python
|
||||
# Basic image with pip
|
||||
image = modal.Image.debian_slim(python_version="3.11").pip_install(
|
||||
"torch==2.1.0", "transformers==4.36.0", "accelerate"
|
||||
)
|
||||
|
||||
# From CUDA base
|
||||
image = modal.Image.from_registry(
|
||||
"nvidia/cuda:12.1.0-cudnn8-devel-ubuntu22.04",
|
||||
add_python="3.11"
|
||||
).pip_install("torch", "transformers")
|
||||
|
||||
# With system packages
|
||||
image = modal.Image.debian_slim().apt_install("git", "ffmpeg").pip_install("whisper")
|
||||
```
|
||||
|
||||
## Persistent storage
|
||||
|
||||
```python
|
||||
volume = modal.Volume.from_name("model-cache", create_if_missing=True)
|
||||
|
||||
@app.function(gpu="A10G", volumes={"/models": volume})
|
||||
def load_model():
|
||||
import os
|
||||
model_path = "/models/llama-7b"
|
||||
if not os.path.exists(model_path):
|
||||
model = download_model()
|
||||
model.save_pretrained(model_path)
|
||||
volume.commit() # Persist changes
|
||||
return load_from_path(model_path)
|
||||
```
|
||||
|
||||
## Web endpoints
|
||||
|
||||
### FastAPI endpoint decorator
|
||||
|
||||
```python
|
||||
@app.function()
|
||||
@modal.fastapi_endpoint(method="POST")
|
||||
def predict(text: str) -> dict:
|
||||
return {"result": model.predict(text)}
|
||||
```
|
||||
|
||||
### Full ASGI app
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI
|
||||
web_app = FastAPI()
|
||||
|
||||
@web_app.post("/predict")
|
||||
async def predict(text: str):
|
||||
return {"result": await model.predict.remote.aio(text)}
|
||||
|
||||
@app.function()
|
||||
@modal.asgi_app()
|
||||
def fastapi_app():
|
||||
return web_app
|
||||
```
|
||||
|
||||
### Web endpoint types
|
||||
|
||||
| Decorator | Use Case |
|
||||
|-----------|----------|
|
||||
| `@modal.fastapi_endpoint()` | Simple function → API |
|
||||
| `@modal.asgi_app()` | Full FastAPI/Starlette apps |
|
||||
| `@modal.wsgi_app()` | Django/Flask apps |
|
||||
| `@modal.web_server(port)` | Arbitrary HTTP servers |
|
||||
|
||||
## Dynamic batching
|
||||
|
||||
```python
|
||||
@app.function()
|
||||
@modal.batched(max_batch_size=32, wait_ms=100)
|
||||
async def batch_predict(inputs: list[str]) -> list[dict]:
|
||||
# Inputs automatically batched
|
||||
return model.batch_predict(inputs)
|
||||
```
|
||||
## Secrets management
|
||||
|
||||
```bash
|
||||
# Create secret
|
||||
modal secret create huggingface HF_TOKEN=hf_xxx
|
||||
```
|
||||
|
||||
```python
|
||||
@app.function(secrets=[modal.Secret.from_name("huggingface")])
|
||||
def download_model():
|
||||
import os
|
||||
token = os.environ["HF_TOKEN"]
|
||||
```
|
||||
|
||||
## Scheduling
|
||||
|
||||
```python
|
||||
@app.function(schedule=modal.Cron("0 0 * * *")) # Daily midnight
|
||||
def daily_job():
|
||||
pass
|
||||
|
||||
@app.function(schedule=modal.Period(hours=1))
|
||||
def hourly_job():
|
||||
pass
|
||||
```
|
||||
|
||||
## Performance optimization
|
||||
|
||||
### Cold start mitigation
|
||||
|
||||
```python
|
||||
# Modal 1.0 autoscaler params: scaledown_window (was container_idle_timeout).
|
||||
# Input concurrency moved to the @modal.concurrent decorator.
|
||||
@app.function(scaledown_window=300) # Keep warm 5 min
|
||||
@modal.concurrent(max_inputs=10) # Handle concurrent requests per container
|
||||
def inference():
|
||||
pass
|
||||
```
|
||||
|
||||
### Model loading best practices
|
||||
|
||||
```python
|
||||
@app.cls(gpu="A100")
|
||||
class Model:
|
||||
@modal.enter() # Run once at container start
|
||||
def load(self):
|
||||
self.model = load_model() # Load during warm-up
|
||||
|
||||
@modal.method()
|
||||
def predict(self, x):
|
||||
return self.model(x)
|
||||
```
|
||||
|
||||
## Parallel processing
|
||||
|
||||
```python
|
||||
@app.function()
|
||||
def process_item(item):
|
||||
return expensive_computation(item)
|
||||
|
||||
@app.function()
|
||||
def run_parallel():
|
||||
items = list(range(1000))
|
||||
# Fan out to parallel containers
|
||||
results = list(process_item.map(items))
|
||||
return results
|
||||
```
|
||||
|
||||
## Common configuration
|
||||
|
||||
```python
|
||||
@app.function(
|
||||
gpu="A100",
|
||||
memory=32768, # 32GB RAM
|
||||
cpu=4, # 4 CPU cores
|
||||
timeout=3600, # 1 hour max
|
||||
scaledown_window=120, # Keep warm 2 min (was container_idle_timeout)
|
||||
retries=3, # Retry on failure
|
||||
max_containers=10, # Max concurrent containers (was concurrency_limit)
|
||||
min_containers=1, # Keep N containers warm (was keep_warm)
|
||||
)
|
||||
def my_function():
|
||||
pass
|
||||
```
|
||||
|
||||
> **Modal 1.0 autoscaler renames** (see the [migration guide](https://modal.com/docs/guide/modal-1-0-migration)):
|
||||
> - `container_idle_timeout` → `scaledown_window`
|
||||
> - `concurrency_limit` → `max_containers`
|
||||
> - `keep_warm` → `min_containers`
|
||||
> - `allow_concurrent_inputs=N` → the `@modal.concurrent(max_inputs=N)` decorator
|
||||
|
||||
## Debugging
|
||||
|
||||
```python
|
||||
# Test locally
|
||||
if __name__ == "__main__":
|
||||
result = my_function.local()
|
||||
|
||||
# View logs
|
||||
# modal app logs my-app
|
||||
```
|
||||
|
||||
## Common issues
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Cold start latency | Increase `scaledown_window`, use `@modal.enter()` |
|
||||
| GPU OOM | Use larger GPU (`A100-80GB`), enable gradient checkpointing |
|
||||
| Image build fails | Pin dependency versions, check CUDA compatibility |
|
||||
| Timeout errors | Increase `timeout`, add checkpointing |
|
||||
|
||||
## References
|
||||
|
||||
- **[Advanced Usage](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\modal/references/advanced-usage.md)** - Multi-GPU, distributed training, cost optimization
|
||||
- **[Troubleshooting](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\modal/references/troubleshooting.md)** - Common issues and solutions
|
||||
|
||||
## Resources
|
||||
|
||||
- **Documentation**: https://modal.com/docs
|
||||
- **Examples**: https://github.com/modal-labs/modal-examples
|
||||
- **Pricing**: https://modal.com/pricing
|
||||
- **Discord**: https://discord.gg/modal
|
||||
@@ -0,0 +1,100 @@
|
||||
---
|
||||
title: "Huggingface Hub — HuggingFace hf CLI: search/download/upload models, datasets"
|
||||
sidebar_label: "Huggingface Hub"
|
||||
description: "HuggingFace hf CLI: search/download/upload models, datasets"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Huggingface Hub
|
||||
|
||||
HuggingFace hf CLI: search/download/upload models, datasets.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/huggingface-hub` |
|
||||
| Path | `optional-skills/mlops\models\huggingface-hub` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Hugging Face |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Hugging Face CLI (`hf`) Reference Guide
|
||||
|
||||
The `hf` command is the modern command-line interface for interacting with the Hugging Face Hub, providing tools to manage repositories, models, datasets, and Spaces.
|
||||
|
||||
> **IMPORTANT:** The `hf` command replaces the now deprecated `huggingface-cli` command.
|
||||
|
||||
## Quick Start
|
||||
* **Installation:** `curl -LsSf https://hf.co/cli/install.sh | bash -s`
|
||||
* **Help:** Use `hf --help` to view all available functions and real-world examples.
|
||||
* **Authentication:** Recommended via `HF_TOKEN` environment variable or the `--token` flag.
|
||||
|
||||
---
|
||||
|
||||
## Core Commands
|
||||
|
||||
### General Operations
|
||||
* `hf download REPO_ID`: Download files from the Hub.
|
||||
* `hf upload REPO_ID`: Upload files/folders (recommended for single-commit; also handles resumable uploads of large directories).
|
||||
* `hf upload-large-folder REPO_ID LOCAL_PATH`: **[Deprecated]** — use `hf upload` instead.
|
||||
* `hf sync`: Sync files between a local directory and a bucket.
|
||||
* `hf env` / `hf version`: View environment and version details.
|
||||
|
||||
### Authentication (`hf auth`)
|
||||
* `login` / `logout`: Manage sessions using tokens from [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens).
|
||||
* `list` / `switch`: Manage and toggle between multiple stored access tokens.
|
||||
* `whoami`: Identify the currently logged-in account.
|
||||
|
||||
### Repository Management (`hf repos`)
|
||||
* `create` / `delete`: Create or permanently remove repositories.
|
||||
* `duplicate`: Clone a model, dataset, or Space to a new ID.
|
||||
* `move`: Transfer a repository between namespaces.
|
||||
* `branch` / `tag`: Manage Git-like references.
|
||||
* `delete-files`: Remove specific files using patterns.
|
||||
|
||||
---
|
||||
|
||||
## Specialized Hub Interactions
|
||||
|
||||
### Datasets & Models
|
||||
* **Datasets:** `hf datasets list`, `info`, and `parquet` (list parquet URLs).
|
||||
* **SQL Queries:** `hf datasets sql SQL` — Execute raw SQL via DuckDB against dataset parquet URLs.
|
||||
* **Models:** `hf models list` and `info`.
|
||||
* **Papers:** `hf papers ls` — View daily papers.
|
||||
|
||||
### Discussions & Pull Requests (`hf discussions`)
|
||||
* Manage the lifecycle of Hub contributions: `list`, `create`, `info`, `comment`, `close`, `reopen`, and `rename`.
|
||||
* `diff`: View changes in a PR.
|
||||
* `merge`: Finalize pull requests.
|
||||
|
||||
### Infrastructure & Compute
|
||||
* **Endpoints:** Deploy and manage Inference Endpoints (`deploy`, `pause`, `resume`, `scale-to-zero`, `catalog`).
|
||||
* **Jobs:** Run compute tasks on HF infrastructure. Includes `hf jobs uv` for running Python scripts with inline dependencies and `stats` for resource monitoring.
|
||||
* **Spaces:** Manage interactive apps. Includes `dev-mode` and `hot-reload` for Python files without full restarts.
|
||||
|
||||
### Storage & Automation
|
||||
* **Buckets:** Full S3-like bucket management (`create`, `cp`, `mv`, `rm`, `sync`).
|
||||
* **Cache:** Manage local storage with `list`, `prune` (remove detached revisions), and `verify` (checksum checks).
|
||||
* **Webhooks:** Automate workflows by managing Hub webhooks (`create`, `watch`, `enable`/`disable`).
|
||||
* **Collections:** Organize Hub items into collections (`add-item`, `update`, `list`).
|
||||
|
||||
---
|
||||
|
||||
## Advanced Usage & Tips
|
||||
|
||||
### Global Flags
|
||||
* `--format json`: Produces machine-readable output for automation.
|
||||
* `-q` / `--quiet`: Limits output to IDs only.
|
||||
|
||||
### Extensions & Skills
|
||||
* **Extensions:** Extend CLI functionality via GitHub repositories using `hf extensions install REPO_ID`.
|
||||
* **Skills:** Manage AI assistant skills with `hf skills add`.
|
||||
@@ -0,0 +1,525 @@
|
||||
---
|
||||
title: "Segment Anything Model — SAM: zero-shot image segmentation via points, boxes, masks"
|
||||
sidebar_label: "Segment Anything Model"
|
||||
description: "SAM: zero-shot image segmentation via points, boxes, masks"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Segment Anything Model
|
||||
|
||||
SAM: zero-shot image segmentation via points, boxes, masks.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/segment-anything-model` |
|
||||
| Path | `optional-skills/mlops\models\segment-anything-model` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `segment-anything`, `transformers>=4.30.0`, `torch>=1.7.0` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Multimodal`, `Image Segmentation`, `Computer Vision`, `SAM`, `Zero-Shot` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Segment Anything Model (SAM)
|
||||
|
||||
Guide to using Meta AI's Segment Anything Model for zero-shot image segmentation.
|
||||
|
||||
## When to use SAM
|
||||
|
||||
**Use SAM when:**
|
||||
- Need to segment any object in images without task-specific training
|
||||
- Building interactive annotation tools with point/box prompts
|
||||
- Generating training data for other vision models
|
||||
- Need zero-shot transfer to new image domains
|
||||
- Building object detection/segmentation pipelines
|
||||
- Processing medical, satellite, or domain-specific images
|
||||
|
||||
**Key features:**
|
||||
- **Zero-shot segmentation**: Works on any image domain without fine-tuning
|
||||
- **Flexible prompts**: Points, bounding boxes, or previous masks
|
||||
- **Automatic segmentation**: Generate all object masks automatically
|
||||
- **High quality**: Trained on 1.1 billion masks from 11 million images
|
||||
- **Multiple model sizes**: ViT-B (fastest), ViT-L, ViT-H (most accurate)
|
||||
- **ONNX export**: Deploy in browsers and edge devices
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **YOLO/Detectron2**: For real-time object detection with classes
|
||||
- **Mask2Former**: For semantic/panoptic segmentation with categories
|
||||
- **GroundingDINO + SAM**: For text-prompted segmentation
|
||||
- **SAM 2**: For video segmentation tasks
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# From GitHub
|
||||
pip install git+https://github.com/facebookresearch/segment-anything.git
|
||||
|
||||
# Optional dependencies
|
||||
pip install opencv-python pycocotools matplotlib
|
||||
|
||||
# Or use HuggingFace transformers
|
||||
pip install transformers
|
||||
```
|
||||
|
||||
### Download checkpoints
|
||||
|
||||
```bash
|
||||
# ViT-H (largest, most accurate) - 2.4GB
|
||||
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
|
||||
|
||||
# ViT-L (medium) - 1.2GB
|
||||
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth
|
||||
|
||||
# ViT-B (smallest, fastest) - 375MB
|
||||
wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth
|
||||
```
|
||||
|
||||
### Basic usage with SamPredictor
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
from segment_anything import sam_model_registry, SamPredictor
|
||||
|
||||
# Load model
|
||||
sam = sam_model_registry["vit_h"](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\models\segment-anything-model/checkpoint="sam_vit_h_4b8939.pth")
|
||||
sam.to(device="cuda")
|
||||
|
||||
# Create predictor
|
||||
predictor = SamPredictor(sam)
|
||||
|
||||
# Set image (computes embeddings once)
|
||||
image = cv2.imread("image.jpg")
|
||||
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
||||
predictor.set_image(image)
|
||||
|
||||
# Predict with point prompts
|
||||
input_point = np.array([[500, 375]]) # (x, y) coordinates
|
||||
input_label = np.array([1]) # 1 = foreground, 0 = background
|
||||
|
||||
masks, scores, logits = predictor.predict(
|
||||
point_coords=input_point,
|
||||
point_labels=input_label,
|
||||
multimask_output=True # Returns 3 mask options
|
||||
)
|
||||
|
||||
# Select best mask
|
||||
best_mask = masks[np.argmax(scores)]
|
||||
```
|
||||
|
||||
### HuggingFace Transformers
|
||||
|
||||
```python
|
||||
import torch
|
||||
from PIL import Image
|
||||
from transformers import SamModel, SamProcessor
|
||||
|
||||
# Load model and processor
|
||||
model = SamModel.from_pretrained("facebook/sam-vit-huge")
|
||||
processor = SamProcessor.from_pretrained("facebook/sam-vit-huge")
|
||||
model.to("cuda")
|
||||
|
||||
# Process image with point prompt
|
||||
image = Image.open("image.jpg")
|
||||
input_points = [[[450, 600]]] # Batch of points
|
||||
|
||||
inputs = processor(image, input_points=input_points, return_tensors="pt")
|
||||
inputs = {k: v.to("cuda") for k, v in inputs.items()}
|
||||
|
||||
# Generate masks
|
||||
with torch.no_grad():
|
||||
outputs = model(**inputs)
|
||||
|
||||
# Post-process masks to original size
|
||||
masks = processor.image_processor.post_process_masks(
|
||||
outputs.pred_masks.cpu(),
|
||||
inputs["original_sizes"].cpu(),
|
||||
inputs["reshaped_input_sizes"].cpu()
|
||||
)
|
||||
```
|
||||
|
||||
## Core concepts
|
||||
|
||||
### Model architecture
|
||||
|
||||
<!-- ascii-guard-ignore -->
|
||||
<!-- ascii-guard-ignore -->
|
||||
```
|
||||
SAM Architecture:
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ Image Encoder │────▶│ Prompt Encoder │────▶│ Mask Decoder │
|
||||
│ (ViT) │ │ (Points/Boxes) │ │ (Transformer) │
|
||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||
│ │ │
|
||||
Image Embeddings Prompt Embeddings Masks + IoU
|
||||
(computed once) (per prompt) predictions
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
### Model variants
|
||||
|
||||
| Model | Checkpoint | Size | Speed | Accuracy |
|
||||
|-------|------------|------|-------|----------|
|
||||
| ViT-H | `vit_h` | 2.4 GB | Slowest | Best |
|
||||
| ViT-L | `vit_l` | 1.2 GB | Medium | Good |
|
||||
| ViT-B | `vit_b` | 375 MB | Fastest | Good |
|
||||
|
||||
### Prompt types
|
||||
|
||||
| Prompt | Description | Use Case |
|
||||
|--------|-------------|----------|
|
||||
| Point (foreground) | Click on object | Single object selection |
|
||||
| Point (background) | Click outside object | Exclude regions |
|
||||
| Bounding box | Rectangle around object | Larger objects |
|
||||
| Previous mask | Low-res mask input | Iterative refinement |
|
||||
|
||||
## Interactive segmentation
|
||||
|
||||
### Point prompts
|
||||
|
||||
```python
|
||||
# Single foreground point
|
||||
input_point = np.array([[500, 375]])
|
||||
input_label = np.array([1])
|
||||
|
||||
masks, scores, logits = predictor.predict(
|
||||
point_coords=input_point,
|
||||
point_labels=input_label,
|
||||
multimask_output=True
|
||||
)
|
||||
|
||||
# Multiple points (foreground + background)
|
||||
input_points = np.array([[500, 375], [600, 400], [450, 300]])
|
||||
input_labels = np.array([1, 1, 0]) # 2 foreground, 1 background
|
||||
|
||||
masks, scores, logits = predictor.predict(
|
||||
point_coords=input_points,
|
||||
point_labels=input_labels,
|
||||
multimask_output=False # Single mask when prompts are clear
|
||||
)
|
||||
```
|
||||
|
||||
### Box prompts
|
||||
|
||||
```python
|
||||
# Bounding box [x1, y1, x2, y2]
|
||||
input_box = np.array([425, 600, 700, 875])
|
||||
|
||||
masks, scores, logits = predictor.predict(
|
||||
box=input_box,
|
||||
multimask_output=False
|
||||
)
|
||||
```
|
||||
|
||||
### Combined prompts
|
||||
|
||||
```python
|
||||
# Box + points for precise control
|
||||
masks, scores, logits = predictor.predict(
|
||||
point_coords=np.array([[500, 375]]),
|
||||
point_labels=np.array([1]),
|
||||
box=np.array([400, 300, 700, 600]),
|
||||
multimask_output=False
|
||||
)
|
||||
```
|
||||
|
||||
### Iterative refinement
|
||||
|
||||
```python
|
||||
# Initial prediction
|
||||
masks, scores, logits = predictor.predict(
|
||||
point_coords=np.array([[500, 375]]),
|
||||
point_labels=np.array([1]),
|
||||
multimask_output=True
|
||||
)
|
||||
|
||||
# Refine with additional point using previous mask
|
||||
masks, scores, logits = predictor.predict(
|
||||
point_coords=np.array([[500, 375], [550, 400]]),
|
||||
point_labels=np.array([1, 0]), # Add background point
|
||||
mask_input=logits[np.argmax(scores)][None, :, :], # Use best mask
|
||||
multimask_output=False
|
||||
)
|
||||
```
|
||||
|
||||
## Automatic mask generation
|
||||
|
||||
### Basic automatic segmentation
|
||||
|
||||
```python
|
||||
from segment_anything import SamAutomaticMaskGenerator
|
||||
|
||||
# Create generator
|
||||
mask_generator = SamAutomaticMaskGenerator(sam)
|
||||
|
||||
# Generate all masks
|
||||
masks = mask_generator.generate(image)
|
||||
|
||||
# Each mask contains:
|
||||
# - segmentation: binary mask
|
||||
# - bbox: [x, y, w, h]
|
||||
# - area: pixel count
|
||||
# - predicted_iou: quality score
|
||||
# - stability_score: robustness score
|
||||
# - point_coords: generating point
|
||||
```
|
||||
|
||||
### Customized generation
|
||||
|
||||
```python
|
||||
mask_generator = SamAutomaticMaskGenerator(
|
||||
model=sam,
|
||||
points_per_side=32, # Grid density (more = more masks)
|
||||
pred_iou_thresh=0.88, # Quality threshold
|
||||
stability_score_thresh=0.95, # Stability threshold
|
||||
crop_n_layers=1, # Multi-scale crops
|
||||
crop_n_points_downscale_factor=2,
|
||||
min_mask_region_area=100, # Remove tiny masks
|
||||
)
|
||||
|
||||
masks = mask_generator.generate(image)
|
||||
```
|
||||
|
||||
### Filtering masks
|
||||
|
||||
```python
|
||||
# Sort by area (largest first)
|
||||
masks = sorted(masks, key=lambda x: x['area'], reverse=True)
|
||||
|
||||
# Filter by predicted IoU
|
||||
high_quality = [m for m in masks if m['predicted_iou'] > 0.9]
|
||||
|
||||
# Filter by stability score
|
||||
stable_masks = [m for m in masks if m['stability_score'] > 0.95]
|
||||
```
|
||||
|
||||
## Batched inference
|
||||
|
||||
### Multiple images
|
||||
|
||||
```python
|
||||
# Process multiple images efficiently
|
||||
images = [cv2.imread(f"image_{i}.jpg") for i in range(10)]
|
||||
|
||||
all_masks = []
|
||||
for image in images:
|
||||
predictor.set_image(image)
|
||||
masks, _, _ = predictor.predict(
|
||||
point_coords=np.array([[500, 375]]),
|
||||
point_labels=np.array([1]),
|
||||
multimask_output=True
|
||||
)
|
||||
all_masks.append(masks)
|
||||
```
|
||||
|
||||
### Multiple prompts per image
|
||||
|
||||
```python
|
||||
# Process multiple prompts efficiently (one image encoding)
|
||||
predictor.set_image(image)
|
||||
|
||||
# Batch of point prompts
|
||||
points = [
|
||||
np.array([[100, 100]]),
|
||||
np.array([[200, 200]]),
|
||||
np.array([[300, 300]])
|
||||
]
|
||||
|
||||
all_masks = []
|
||||
for point in points:
|
||||
masks, scores, _ = predictor.predict(
|
||||
point_coords=point,
|
||||
point_labels=np.array([1]),
|
||||
multimask_output=True
|
||||
)
|
||||
all_masks.append(masks[np.argmax(scores)])
|
||||
```
|
||||
|
||||
## ONNX deployment
|
||||
|
||||
### Export model
|
||||
|
||||
```bash
|
||||
python scripts/export_onnx_model.py \
|
||||
--checkpoint sam_vit_h_4b8939.pth \
|
||||
--model-type vit_h \
|
||||
--output sam_onnx.onnx \
|
||||
--return-single-mask
|
||||
```
|
||||
|
||||
### Use ONNX model
|
||||
|
||||
```python
|
||||
import onnxruntime
|
||||
|
||||
# Load ONNX model
|
||||
ort_session = onnxruntime.InferenceSession("sam_onnx.onnx")
|
||||
|
||||
# Run inference (image embeddings computed separately)
|
||||
masks = ort_session.run(
|
||||
None,
|
||||
{
|
||||
"image_embeddings": image_embeddings,
|
||||
"point_coords": point_coords,
|
||||
"point_labels": point_labels,
|
||||
"mask_input": np.zeros((1, 1, 256, 256), dtype=np.float32),
|
||||
"has_mask_input": np.array([0], dtype=np.float32),
|
||||
"orig_im_size": np.array([h, w], dtype=np.float32)
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: Annotation tool
|
||||
|
||||
```python
|
||||
import cv2
|
||||
|
||||
# Load model
|
||||
predictor = SamPredictor(sam)
|
||||
predictor.set_image(image)
|
||||
|
||||
def on_click(event, x, y, flags, param):
|
||||
if event == cv2.EVENT_LBUTTONDOWN:
|
||||
# Foreground point
|
||||
masks, scores, _ = predictor.predict(
|
||||
point_coords=np.array([[x, y]]),
|
||||
point_labels=np.array([1]),
|
||||
multimask_output=True
|
||||
)
|
||||
# Display best mask
|
||||
display_mask(masks[np.argmax(scores)])
|
||||
```
|
||||
|
||||
### Workflow 2: Object extraction
|
||||
|
||||
```python
|
||||
def extract_object(image, point):
|
||||
"""Extract object at point with transparent background."""
|
||||
predictor.set_image(image)
|
||||
|
||||
masks, scores, _ = predictor.predict(
|
||||
point_coords=np.array([point]),
|
||||
point_labels=np.array([1]),
|
||||
multimask_output=True
|
||||
)
|
||||
|
||||
best_mask = masks[np.argmax(scores)]
|
||||
|
||||
# Create RGBA output
|
||||
rgba = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
|
||||
rgba[:, :, :3] = image
|
||||
rgba[:, :, 3] = best_mask * 255
|
||||
|
||||
return rgba
|
||||
```
|
||||
|
||||
### Workflow 3: Medical image segmentation
|
||||
|
||||
```python
|
||||
# Process medical images (grayscale to RGB)
|
||||
medical_image = cv2.imread("scan.png", cv2.IMREAD_GRAYSCALE)
|
||||
rgb_image = cv2.cvtColor(medical_image, cv2.COLOR_GRAY2RGB)
|
||||
|
||||
predictor.set_image(rgb_image)
|
||||
|
||||
# Segment region of interest
|
||||
masks, scores, _ = predictor.predict(
|
||||
box=np.array([x1, y1, x2, y2]), # ROI bounding box
|
||||
multimask_output=True
|
||||
)
|
||||
```
|
||||
|
||||
## Output format
|
||||
|
||||
### Mask data structure
|
||||
|
||||
```python
|
||||
# SamAutomaticMaskGenerator output
|
||||
{
|
||||
"segmentation": np.ndarray, # H×W binary mask
|
||||
"bbox": [x, y, w, h], # Bounding box
|
||||
"area": int, # Pixel count
|
||||
"predicted_iou": float, # 0-1 quality score
|
||||
"stability_score": float, # 0-1 robustness score
|
||||
"crop_box": [x, y, w, h], # Generation crop region
|
||||
"point_coords": [[x, y]], # Input point
|
||||
}
|
||||
```
|
||||
|
||||
### COCO RLE format
|
||||
|
||||
```python
|
||||
from pycocotools import mask as mask_utils
|
||||
|
||||
# Encode mask to RLE
|
||||
rle = mask_utils.encode(np.asfortranarray(mask.astype(np.uint8)))
|
||||
rle["counts"] = rle["counts"].decode("utf-8")
|
||||
|
||||
# Decode RLE to mask
|
||||
decoded_mask = mask_utils.decode(rle)
|
||||
```
|
||||
|
||||
## Performance optimization
|
||||
|
||||
### GPU memory
|
||||
|
||||
```python
|
||||
# Use smaller model for limited VRAM
|
||||
sam = sam_model_registry["vit_b"](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\models\segment-anything-model/checkpoint="sam_vit_b_01ec64.pth")
|
||||
|
||||
# Process images in batches
|
||||
# Clear CUDA cache between large batches
|
||||
torch.cuda.empty_cache()
|
||||
```
|
||||
|
||||
### Speed optimization
|
||||
|
||||
```python
|
||||
# Use half precision
|
||||
sam = sam.half()
|
||||
|
||||
# Reduce points for automatic generation
|
||||
mask_generator = SamAutomaticMaskGenerator(
|
||||
model=sam,
|
||||
points_per_side=16, # Default is 32
|
||||
)
|
||||
|
||||
# Use ONNX for deployment
|
||||
# Export with --return-single-mask for faster inference
|
||||
```
|
||||
|
||||
## Common issues
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Out of memory | Use ViT-B model, reduce image size |
|
||||
| Slow inference | Use ViT-B, reduce points_per_side |
|
||||
| Poor mask quality | Try different prompts, use box + points |
|
||||
| Edge artifacts | Use stability_score filtering |
|
||||
| Small objects missed | Increase points_per_side |
|
||||
|
||||
## References
|
||||
|
||||
- **[Advanced Usage](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\models\segment-anything-model/references/advanced-usage.md)** - Batching, fine-tuning, integration
|
||||
- **[Troubleshooting](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\models\segment-anything-model/references/troubleshooting.md)** - Common issues and solutions
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/facebookresearch/segment-anything
|
||||
- **Paper**: https://arxiv.org/abs/2304.02643
|
||||
- **Demo**: https://segment-anything.com
|
||||
- **SAM 2 (Video)**: https://github.com/facebookresearch/segment-anything-2
|
||||
- **HuggingFace**: https://huggingface.co/facebook/sam-vit-huge
|
||||
@@ -0,0 +1,415 @@
|
||||
---
|
||||
title: "Nemo Curator — Curate LLM training data: dedupe, filter, PII redaction"
|
||||
sidebar_label: "Nemo Curator"
|
||||
description: "Curate LLM training data: dedupe, filter, PII redaction"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Nemo Curator
|
||||
|
||||
Curate LLM training data: dedupe, filter, PII redaction.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/nemo-curator` |
|
||||
| Path | `optional-skills/mlops\nemo-curator` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `nemo-curator`, `cudf`, `dask`, `rapids` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Data Processing`, `NeMo Curator`, `Data Curation`, `GPU Acceleration`, `Deduplication`, `Quality Filtering`, `NVIDIA`, `RAPIDS`, `PII Redaction`, `Multimodal`, `LLM Training Data` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# NeMo Curator - GPU-Accelerated Data Curation
|
||||
|
||||
NVIDIA's toolkit for preparing high-quality training data for LLMs.
|
||||
|
||||
## When to use NeMo Curator
|
||||
|
||||
**Use NeMo Curator when:**
|
||||
- Preparing LLM training data from web scrapes (Common Crawl)
|
||||
- Need fast deduplication (16× faster than CPU)
|
||||
- Curating multi-modal datasets (text, images, video, audio)
|
||||
- Filtering low-quality or toxic content
|
||||
- Scaling data processing across GPU cluster
|
||||
|
||||
**Performance**:
|
||||
- **16× faster** fuzzy deduplication (8TB RedPajama v2)
|
||||
- **40% lower TCO** vs CPU alternatives
|
||||
- **Near-linear scaling** across GPU nodes
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **datatrove**: CPU-based, open-source data processing
|
||||
- **dolma**: Allen AI's data toolkit
|
||||
- **Ray Data**: General ML data processing (no curation focus)
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# NeMo Curator 1.x installs with uv. Extras use hyphens (PyPI-normalized):
|
||||
# text-cuda12 / text-cpu (and image/video/audio/math variants), or `all`.
|
||||
|
||||
# Text curation (CUDA 12)
|
||||
uv pip install "nemo-curator[text-cuda12]"
|
||||
|
||||
# All modalities
|
||||
uv pip install "nemo-curator[all]"
|
||||
|
||||
# CPU-only text (slower)
|
||||
uv pip install "nemo-curator[text-cpu]"
|
||||
```
|
||||
|
||||
### Basic text curation pipeline
|
||||
|
||||
> **Major version rewrite (1.x):** NeMo Curator was rewritten around a **Ray-based
|
||||
> pipeline/stage architecture**. The old `DocumentDataset` + `nemo_curator.modules.*` /
|
||||
> `ScoreFilter` / `Modify` call-the-object-on-a-dataset API from 0.x is gone. In 1.x you
|
||||
> compose `ProcessingStage`s into a `Pipeline` and run it with an executor. The exact
|
||||
> stage/import surface differs per modality — treat the examples in this skill below as
|
||||
> **conceptual** (0.x-style) and follow the current
|
||||
> [quickstart](https://github.com/NVIDIA-NeMo/Curator/blob/main/tutorials/quickstart.py)
|
||||
> and [text guide](https://docs.nvidia.com/nemo/curator/latest/get-started/text) for the
|
||||
> exact 1.x APIs rather than copying imports verbatim.
|
||||
|
||||
Shape of a 1.x pipeline (from the upstream quickstart):
|
||||
|
||||
```python
|
||||
from nemo_curator.pipeline import Pipeline
|
||||
from nemo_curator.stages.base import ProcessingStage
|
||||
from nemo_curator.stages.resources import Resources
|
||||
from nemo_curator.backends.xenna import XennaExecutor
|
||||
from nemo_curator.core.client import RayClient
|
||||
|
||||
# 1. Define/compose stages (load -> filter -> dedupe -> classify -> write).
|
||||
# Each stage declares its own Resources (CPU cores, GPU memory, replicas).
|
||||
pipeline = Pipeline(name="curation", stages=[...])
|
||||
|
||||
# 2. Run it with an executor (Ray-backed).
|
||||
client = RayClient()
|
||||
client.start()
|
||||
pipeline.run(XennaExecutor())
|
||||
client.stop()
|
||||
```
|
||||
|
||||
The 0.x-style snippets in the sections that follow illustrate the *concepts* (quality
|
||||
filtering, exact/fuzzy/semantic dedup, PII redaction, classifier filtering). For runnable
|
||||
1.x code, map each concept onto the corresponding stage from the modality guide.
|
||||
|
||||
## Data curation pipeline
|
||||
|
||||
### Stage 1: Quality filtering
|
||||
|
||||
```python
|
||||
from nemo_curator.filters import (
|
||||
WordCountFilter,
|
||||
RepeatedLinesFilter,
|
||||
UrlRatioFilter,
|
||||
NonAlphaNumericFilter
|
||||
)
|
||||
|
||||
# Apply 30+ heuristic filters
|
||||
from nemo_curator import ScoreFilter
|
||||
|
||||
# Word count filter
|
||||
dataset = dataset.filter(WordCountFilter(min_words=50, max_words=100000))
|
||||
|
||||
# Remove repetitive content
|
||||
dataset = dataset.filter(RepeatedLinesFilter(max_repeated_line_fraction=0.3))
|
||||
|
||||
# URL ratio filter
|
||||
dataset = dataset.filter(UrlRatioFilter(max_url_ratio=0.2))
|
||||
```
|
||||
|
||||
### Stage 2: Deduplication
|
||||
|
||||
**Exact deduplication**:
|
||||
```python
|
||||
from nemo_curator.modules import ExactDuplicates
|
||||
|
||||
# Remove exact duplicates
|
||||
deduped = ExactDuplicates(id_field="id", text_field="text")(dataset)
|
||||
```
|
||||
|
||||
**Fuzzy deduplication** (16× faster on GPU):
|
||||
```python
|
||||
from nemo_curator.modules import FuzzyDuplicates
|
||||
|
||||
# MinHash + LSH deduplication
|
||||
fuzzy_dedup = FuzzyDuplicates(
|
||||
id_field="id",
|
||||
text_field="text",
|
||||
num_hashes=260, # MinHash parameters
|
||||
num_buckets=20,
|
||||
hash_method="md5"
|
||||
)
|
||||
|
||||
deduped = fuzzy_dedup(dataset)
|
||||
```
|
||||
|
||||
**Semantic deduplication**:
|
||||
```python
|
||||
from nemo_curator.modules import SemanticDuplicates
|
||||
|
||||
# Embedding-based deduplication
|
||||
semantic_dedup = SemanticDuplicates(
|
||||
id_field="id",
|
||||
text_field="text",
|
||||
embedding_model="sentence-transformers/all-MiniLM-L6-v2",
|
||||
threshold=0.8 # Cosine similarity threshold
|
||||
)
|
||||
|
||||
deduped = semantic_dedup(dataset)
|
||||
```
|
||||
|
||||
### Stage 3: PII redaction
|
||||
|
||||
```python
|
||||
from nemo_curator.modules import Modify
|
||||
from nemo_curator.modifiers import PIIRedactor
|
||||
|
||||
# Redact personally identifiable information
|
||||
pii_redactor = PIIRedactor(
|
||||
supported_entities=["EMAIL_ADDRESS", "PHONE_NUMBER", "PERSON", "LOCATION"],
|
||||
anonymize_action="replace" # or "redact"
|
||||
)
|
||||
|
||||
redacted = Modify(pii_redactor)(dataset)
|
||||
```
|
||||
|
||||
### Stage 4: Classifier filtering
|
||||
|
||||
```python
|
||||
from nemo_curator.classifiers import QualityClassifier
|
||||
|
||||
# Quality classification
|
||||
quality_clf = QualityClassifier(
|
||||
model_path="nvidia/quality-classifier-deberta",
|
||||
batch_size=256,
|
||||
device="cuda"
|
||||
)
|
||||
|
||||
# Filter low-quality documents
|
||||
high_quality = dataset.filter(lambda doc: quality_clf(doc["text"]) > 0.5)
|
||||
```
|
||||
|
||||
## GPU acceleration
|
||||
|
||||
### GPU vs CPU performance
|
||||
|
||||
| Operation | CPU (16 cores) | GPU (A100) | Speedup |
|
||||
|-----------|----------------|------------|---------|
|
||||
| Fuzzy dedup (8TB) | 120 hours | 7.5 hours | 16× |
|
||||
| Exact dedup (1TB) | 8 hours | 0.5 hours | 16× |
|
||||
| Quality filtering | 2 hours | 0.2 hours | 10× |
|
||||
|
||||
### Multi-GPU scaling
|
||||
|
||||
```python
|
||||
from nemo_curator import get_client
|
||||
import dask_cuda
|
||||
|
||||
# Initialize GPU cluster
|
||||
client = get_client(cluster_type="gpu", n_workers=8)
|
||||
|
||||
# Process with 8 GPUs
|
||||
deduped = FuzzyDuplicates(...)(dataset)
|
||||
```
|
||||
|
||||
## Multi-modal curation
|
||||
|
||||
### Image curation
|
||||
|
||||
```python
|
||||
from nemo_curator.image import (
|
||||
AestheticFilter,
|
||||
NSFWFilter,
|
||||
CLIPEmbedder
|
||||
)
|
||||
|
||||
# Aesthetic scoring
|
||||
aesthetic_filter = AestheticFilter(threshold=5.0)
|
||||
filtered_images = aesthetic_filter(image_dataset)
|
||||
|
||||
# NSFW detection
|
||||
nsfw_filter = NSFWFilter(threshold=0.9)
|
||||
safe_images = nsfw_filter(filtered_images)
|
||||
|
||||
# Generate CLIP embeddings
|
||||
clip_embedder = CLIPEmbedder(model="openai/clip-vit-base-patch32")
|
||||
image_embeddings = clip_embedder(safe_images)
|
||||
```
|
||||
|
||||
### Video curation
|
||||
|
||||
```python
|
||||
from nemo_curator.video import (
|
||||
SceneDetector,
|
||||
ClipExtractor,
|
||||
InternVideo2Embedder
|
||||
)
|
||||
|
||||
# Detect scenes
|
||||
scene_detector = SceneDetector(threshold=27.0)
|
||||
scenes = scene_detector(video_dataset)
|
||||
|
||||
# Extract clips
|
||||
clip_extractor = ClipExtractor(min_duration=2.0, max_duration=10.0)
|
||||
clips = clip_extractor(scenes)
|
||||
|
||||
# Generate embeddings
|
||||
video_embedder = InternVideo2Embedder()
|
||||
video_embeddings = video_embedder(clips)
|
||||
```
|
||||
|
||||
### Audio curation
|
||||
|
||||
```python
|
||||
from nemo_curator.audio import (
|
||||
ASRInference,
|
||||
WERFilter,
|
||||
DurationFilter
|
||||
)
|
||||
|
||||
# ASR transcription
|
||||
asr = ASRInference(model="nvidia/stt_en_fastconformer_hybrid_large_pc")
|
||||
transcribed = asr(audio_dataset)
|
||||
|
||||
# Filter by WER (word error rate)
|
||||
wer_filter = WERFilter(max_wer=0.3)
|
||||
high_quality_audio = wer_filter(transcribed)
|
||||
|
||||
# Duration filtering
|
||||
duration_filter = DurationFilter(min_duration=1.0, max_duration=30.0)
|
||||
filtered_audio = duration_filter(high_quality_audio)
|
||||
```
|
||||
|
||||
## Common patterns
|
||||
|
||||
### Web scrape curation (Common Crawl)
|
||||
|
||||
```python
|
||||
from nemo_curator import ScoreFilter, Modify
|
||||
from nemo_curator.filters import *
|
||||
from nemo_curator.modules import *
|
||||
from nemo_curator.datasets import DocumentDataset
|
||||
|
||||
# Load Common Crawl data
|
||||
dataset = DocumentDataset.read_parquet("common_crawl/*.parquet")
|
||||
|
||||
# Pipeline
|
||||
pipeline = [
|
||||
# 1. Quality filtering
|
||||
WordCountFilter(min_words=100, max_words=50000),
|
||||
RepeatedLinesFilter(max_repeated_line_fraction=0.2),
|
||||
SymbolToWordRatioFilter(max_symbol_to_word_ratio=0.3),
|
||||
UrlRatioFilter(max_url_ratio=0.3),
|
||||
|
||||
# 2. Language filtering
|
||||
LanguageIdentificationFilter(target_languages=["en"]),
|
||||
|
||||
# 3. Deduplication
|
||||
ExactDuplicates(id_field="id", text_field="text"),
|
||||
FuzzyDuplicates(id_field="id", text_field="text", num_hashes=260),
|
||||
|
||||
# 4. PII redaction
|
||||
PIIRedactor(),
|
||||
|
||||
# 5. NSFW filtering
|
||||
NSFWClassifier(threshold=0.8)
|
||||
]
|
||||
|
||||
# Execute
|
||||
for stage in pipeline:
|
||||
dataset = stage(dataset)
|
||||
|
||||
# Save
|
||||
dataset.to_parquet("curated_common_crawl/")
|
||||
```
|
||||
|
||||
### Distributed processing
|
||||
|
||||
```python
|
||||
from nemo_curator import get_client
|
||||
from dask_cuda import LocalCUDACluster
|
||||
|
||||
# Multi-GPU cluster
|
||||
cluster = LocalCUDACluster(n_workers=8)
|
||||
client = get_client(cluster=cluster)
|
||||
|
||||
# Process large dataset
|
||||
dataset = DocumentDataset.read_parquet("s3://large_dataset/*.parquet")
|
||||
deduped = FuzzyDuplicates(...)(dataset)
|
||||
|
||||
# Cleanup
|
||||
client.close()
|
||||
cluster.close()
|
||||
```
|
||||
|
||||
## Performance benchmarks
|
||||
|
||||
### Fuzzy deduplication (8TB RedPajama v2)
|
||||
|
||||
- **CPU (256 cores)**: 120 hours
|
||||
- **GPU (8× A100)**: 7.5 hours
|
||||
- **Speedup**: 16×
|
||||
|
||||
### Exact deduplication (1TB)
|
||||
|
||||
- **CPU (64 cores)**: 8 hours
|
||||
- **GPU (4× A100)**: 0.5 hours
|
||||
- **Speedup**: 16×
|
||||
|
||||
### Quality filtering (100GB)
|
||||
|
||||
- **CPU (32 cores)**: 2 hours
|
||||
- **GPU (2× A100)**: 0.2 hours
|
||||
- **Speedup**: 10×
|
||||
|
||||
## Cost comparison
|
||||
|
||||
**CPU-based curation** (AWS c5.18xlarge × 10):
|
||||
- Cost: $3.60/hour × 10 = $36/hour
|
||||
- Time for 8TB: 120 hours
|
||||
- **Total**: $4,320
|
||||
|
||||
**GPU-based curation** (AWS p4d.24xlarge × 2):
|
||||
- Cost: $32.77/hour × 2 = $65.54/hour
|
||||
- Time for 8TB: 7.5 hours
|
||||
- **Total**: $491.55
|
||||
|
||||
**Savings**: 89% reduction ($3,828 saved)
|
||||
|
||||
## Supported data formats
|
||||
|
||||
- **Input**: Parquet, JSONL, CSV
|
||||
- **Output**: Parquet (recommended), JSONL
|
||||
- **WebDataset**: TAR archives for multi-modal
|
||||
|
||||
## Use cases
|
||||
|
||||
**Production deployments**:
|
||||
- NVIDIA used NeMo Curator to prepare Nemotron-4 training data
|
||||
- Open-source datasets curated: RedPajama v2, The Pile
|
||||
|
||||
## References
|
||||
|
||||
- **[Filtering Guide](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\nemo-curator/references/filtering.md)** - 30+ quality filters, heuristics
|
||||
- **[Deduplication Guide](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\nemo-curator/references/deduplication.md)** - Exact, fuzzy, semantic methods
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/NVIDIA-NeMo/Curator
|
||||
- **Docs**: https://docs.nvidia.com/nemo/curator/latest/
|
||||
- **Version**: 1.2.0 (1.x is a Ray-based pipeline rewrite — see the quickstart before copying 0.x snippets)
|
||||
- **License**: Apache 2.0
|
||||
@@ -0,0 +1,360 @@
|
||||
---
|
||||
title: "Obliteratus — OBLITERATUS: abliterate LLM refusals (diff-in-means)"
|
||||
sidebar_label: "Obliteratus"
|
||||
description: "OBLITERATUS: abliterate LLM refusals (diff-in-means)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Obliteratus
|
||||
|
||||
OBLITERATUS: abliterate LLM refusals (diff-in-means).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/obliteratus` |
|
||||
| Path | `optional-skills/mlops\obliteratus` |
|
||||
| Version | `2.0.0` |
|
||||
| Author | Hermes Agent |
|
||||
| License | MIT |
|
||||
| Dependencies | `obliteratus`, `torch`, `transformers`, `bitsandbytes`, `accelerate`, `safetensors` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Abliteration`, `Uncensoring`, `Refusal-Removal`, `LLM`, `Weight-Projection`, `SVD`, `Mechanistic-Interpretability`, `HuggingFace`, `Model-Surgery` |
|
||||
| Related skills | [`serving-llms-vllm`](/docs/user-guide/skills/optional/mlops/mlops-inference-serving-llms-vllm), [`llama-cpp`](/docs/user-guide/skills/optional/mlops/mlops-inference-llama-cpp), [`huggingface-tokenizers`](/docs/user-guide/skills/optional/mlops/mlops-huggingface-tokenizers) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# OBLITERATUS Skill
|
||||
|
||||
## What's inside
|
||||
|
||||
9 CLI methods, 28 analysis modules, 116 model presets across 5 compute tiers, tournament evaluation, and telemetry-driven recommendations.
|
||||
|
||||
Remove refusal behaviors (guardrails) from open-weight LLMs without retraining or fine-tuning. Uses mechanistic interpretability techniques — including diff-in-means, SVD, whitened SVD, LEACE concept erasure, SAE decomposition, Bayesian kernel projection, and more — to identify and surgically excise refusal directions from model weights while preserving reasoning capabilities.
|
||||
|
||||
**License warning:** OBLITERATUS is AGPL-3.0. NEVER import it as a Python library. Always invoke via CLI (`obliteratus` command) or subprocess. This keeps Hermes Agent's MIT license clean.
|
||||
|
||||
## Video Guide
|
||||
|
||||
Walkthrough of OBLITERATUS used by a Hermes agent to abliterate Gemma:
|
||||
https://www.youtube.com/watch?v=8fG9BrNTeHs ("OBLITERATUS: An AI Agent Removed Gemma 4's Safety Guardrails")
|
||||
|
||||
Useful when the user wants a visual overview of the end-to-end workflow before running it themselves.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Trigger when the user:
|
||||
- Wants to "uncensor" or "abliterate" an LLM
|
||||
- Asks about removing refusal/guardrails from a model
|
||||
- Wants to create an uncensored version of Llama, Qwen, Mistral, etc.
|
||||
- Mentions "refusal removal", "abliteration", "weight projection"
|
||||
- Wants to analyze how a model's refusal mechanism works
|
||||
- References OBLITERATUS, abliterator, or refusal directions
|
||||
|
||||
## Step 1: Installation
|
||||
|
||||
Check if already installed:
|
||||
```bash
|
||||
obliteratus --version 2>/dev/null && echo "INSTALLED" || echo "NOT INSTALLED"
|
||||
```
|
||||
|
||||
If not installed, clone and install from GitHub:
|
||||
```bash
|
||||
git clone https://github.com/elder-plinius/OBLITERATUS.git
|
||||
cd OBLITERATUS
|
||||
pip install -e .
|
||||
# For Gradio web UI support:
|
||||
# pip install -e ".[spaces]"
|
||||
```
|
||||
|
||||
**IMPORTANT:** Confirm with user before installing. This pulls in ~5-10GB of dependencies (PyTorch, Transformers, bitsandbytes, etc.).
|
||||
|
||||
## Step 2: Check Hardware
|
||||
|
||||
Before anything, check what GPU is available:
|
||||
```bash
|
||||
python3 -c "
|
||||
import torch
|
||||
if torch.cuda.is_available():
|
||||
gpu = torch.cuda.get_device_name(0)
|
||||
vram = torch.cuda.get_device_properties(0).total_memory / 1024**3
|
||||
print(f'GPU: {gpu}')
|
||||
print(f'VRAM: {vram:.1f} GB')
|
||||
if vram < 4: print('TIER: tiny (models under 1B)')
|
||||
elif vram < 8: print('TIER: small (models 1-4B)')
|
||||
elif vram < 16: print('TIER: medium (models 4-9B with 4bit quant)')
|
||||
elif vram < 32: print('TIER: large (models 8-32B with 4bit quant)')
|
||||
else: print('TIER: frontier (models 32B+)')
|
||||
else:
|
||||
print('NO GPU - only tiny models (under 1B) on CPU')
|
||||
"
|
||||
```
|
||||
|
||||
### VRAM Requirements (with 4-bit quantization)
|
||||
|
||||
| VRAM | Max Model Size | Example Models |
|
||||
|:---------|:----------------|:--------------------------------------------|
|
||||
| CPU only | ~1B params | GPT-2, TinyLlama, SmolLM |
|
||||
| 4-8 GB | ~4B params | Qwen2.5-1.5B, Phi-3.5 mini, Llama 3.2 3B |
|
||||
| 8-16 GB | ~9B params | Llama 3.1 8B, Mistral 7B, Gemma 2 9B |
|
||||
| 24 GB | ~32B params | Qwen3-32B, Llama 3.1 70B (tight), Command-R |
|
||||
| 48 GB+ | ~72B+ params | Qwen2.5-72B, DeepSeek-R1 |
|
||||
| Multi-GPU| 200B+ params | Llama 3.1 405B, DeepSeek-V3 (685B MoE) |
|
||||
|
||||
## Step 3: Browse Available Models & Get Recommendations
|
||||
|
||||
```bash
|
||||
# Browse models by compute tier
|
||||
obliteratus models --tier medium
|
||||
|
||||
# Get architecture info for a specific model
|
||||
obliteratus info <model_name>
|
||||
|
||||
# Get telemetry-driven recommendation for best method & params
|
||||
obliteratus recommend <model_name>
|
||||
obliteratus recommend <model_name> --insights # global cross-architecture rankings
|
||||
```
|
||||
|
||||
## Step 4: Choose a Method
|
||||
|
||||
### Method Selection Guide
|
||||
**Default / recommended for most cases: `advanced`.** It uses multi-direction SVD with norm-preserving projection and is well-tested.
|
||||
|
||||
| Situation | Recommended Method | Why |
|
||||
|:----------------------------------|:-------------------|:-----------------------------------------|
|
||||
| Default / most models | `advanced` | Multi-direction SVD, norm-preserving, reliable |
|
||||
| Quick test / prototyping | `basic` | Fast, simple, good enough to evaluate |
|
||||
| Dense model (Llama, Mistral) | `advanced` | Multi-direction, norm-preserving |
|
||||
| MoE model (DeepSeek, Mixtral) | `nuclear` | Expert-granular, handles MoE complexity |
|
||||
| Reasoning model (R1 distills) | `surgical` | CoT-aware, preserves chain-of-thought |
|
||||
| Stubborn refusals persist | `aggressive` | Whitened SVD + head surgery + jailbreak |
|
||||
| Want reversible changes | Use steering vectors (see Analysis section) |
|
||||
| Maximum quality, time no object | `optimized` | Bayesian search for best parameters |
|
||||
| Experimental auto-detection | `informed` | Auto-detects alignment type — experimental, may not always outperform advanced |
|
||||
|
||||
### 9 CLI Methods
|
||||
- **basic** — Single refusal direction via diff-in-means. Fast (~5-10 min for 8B).
|
||||
- **advanced** (DEFAULT, RECOMMENDED) — Multiple SVD directions, norm-preserving projection, 2 refinement passes. Medium speed (~10-20 min).
|
||||
- **aggressive** — Whitened SVD + jailbreak-contrastive + attention head surgery. Higher risk of coherence damage.
|
||||
- **spectral_cascade** — DCT frequency-domain decomposition. Research/novel approach.
|
||||
- **informed** — Runs analysis DURING abliteration to auto-configure. Experimental — slower and less predictable than advanced.
|
||||
- **surgical** — SAE features + neuron masking + head surgery + per-expert. Very slow (~1-2 hrs). Best for reasoning models.
|
||||
- **optimized** — Bayesian hyperparameter search (Optuna TPE). Longest runtime but finds optimal parameters.
|
||||
- **inverted** — Flips the refusal direction. Model becomes actively willing.
|
||||
- **nuclear** — Maximum force combo for stubborn MoE models. Expert-granular.
|
||||
|
||||
### Direction Extraction Methods (--direction-method flag)
|
||||
- **diff_means** (default) — Simple difference-in-means between refused/complied activations. Robust.
|
||||
- **svd** — Multi-direction SVD extraction. Better for complex alignment.
|
||||
- **leace** — LEACE (Linear Erasure via Closed-form Estimation). Optimal linear erasure.
|
||||
|
||||
### 4 Python-API-Only Methods
|
||||
(NOT available via CLI — require Python import, which violates AGPL boundary. Mention to user only if they explicitly want to use OBLITERATUS as a library in their own AGPL project.)
|
||||
- failspy, gabliteration, heretic, rdo
|
||||
|
||||
## Step 5: Run Abliteration
|
||||
|
||||
### Standard usage
|
||||
```bash
|
||||
# Default method (advanced) — recommended for most models
|
||||
obliteratus obliterate <model_name> --method advanced --output-dir ./abliterated-models
|
||||
|
||||
# With 4-bit quantization (saves VRAM)
|
||||
obliteratus obliterate <model_name> --method advanced --quantization 4bit --output-dir ./abliterated-models
|
||||
|
||||
# Large models (70B+) — conservative defaults
|
||||
obliteratus obliterate <model_name> --method advanced --quantization 4bit --large-model --output-dir ./abliterated-models
|
||||
```
|
||||
|
||||
### Fine-tuning parameters
|
||||
```bash
|
||||
obliteratus obliterate <model_name> \
|
||||
--method advanced \
|
||||
--direction-method diff_means \
|
||||
--n-directions 4 \
|
||||
--refinement-passes 2 \
|
||||
--regularization 0.1 \
|
||||
--quantization 4bit \
|
||||
--output-dir ./abliterated-models \
|
||||
--contribute # opt-in telemetry for community research
|
||||
```
|
||||
|
||||
### Key flags
|
||||
| Flag | Description | Default |
|
||||
|:-----|:------------|:--------|
|
||||
| `--method` | Abliteration method | advanced |
|
||||
| `--direction-method` | Direction extraction | diff_means |
|
||||
| `--n-directions` | Number of refusal directions (1-32) | method-dependent |
|
||||
| `--refinement-passes` | Iterative passes (1-5) | 2 |
|
||||
| `--regularization` | Regularization strength (0.0-1.0) | 0.1 |
|
||||
| `--quantization` | Load in 4bit or 8bit | none (full precision) |
|
||||
| `--large-model` | Conservative defaults for 120B+ | false |
|
||||
| `--output-dir` | Where to save the abliterated model | ./obliterated_model |
|
||||
| `--contribute` | Share anonymized results for research | false |
|
||||
| `--verify-sample-size` | Number of test prompts for refusal check | 20 |
|
||||
| `--dtype` | Model dtype (float16, bfloat16) | auto |
|
||||
|
||||
### Other execution modes
|
||||
```bash
|
||||
# Interactive guided mode (hardware → model → preset)
|
||||
obliteratus interactive
|
||||
|
||||
# Web UI (Gradio)
|
||||
obliteratus ui --port 7860
|
||||
|
||||
# Run a full ablation study from YAML config
|
||||
obliteratus run config.yaml --preset quick
|
||||
|
||||
# Tournament: pit all methods against each other
|
||||
obliteratus tourney <model_name>
|
||||
```
|
||||
|
||||
## Step 6: Verify Results
|
||||
|
||||
After abliteration, check the output metrics:
|
||||
|
||||
| Metric | Good Value | Warning |
|
||||
|:-------|:-----------|:--------|
|
||||
| Refusal rate | < 5% (ideally ~0%) | > 10% means refusals persist |
|
||||
| Perplexity change | < 10% increase | > 15% means coherence damage |
|
||||
| KL divergence | < 0.1 | > 0.5 means significant distribution shift |
|
||||
| Coherence | High / passes qualitative check | Degraded responses, repetition |
|
||||
|
||||
### If refusals persist (> 10%)
|
||||
1. Try `aggressive` method
|
||||
2. Increase `--n-directions` (e.g., 8 or 16)
|
||||
3. Add `--refinement-passes 3`
|
||||
4. Try `--direction-method svd` instead of diff_means
|
||||
|
||||
### If coherence is damaged (perplexity > 15% increase)
|
||||
1. Reduce `--n-directions` (try 2)
|
||||
2. Increase `--regularization` (try 0.3)
|
||||
3. Reduce `--refinement-passes` to 1
|
||||
4. Try `basic` method (gentler)
|
||||
|
||||
## Step 7: Use the Abliterated Model
|
||||
|
||||
The output is a standard HuggingFace model directory.
|
||||
|
||||
```bash
|
||||
# Test locally with transformers
|
||||
python3 -c "
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
model = AutoModelForCausalLM.from_pretrained('./abliterated-models/<model>')
|
||||
tokenizer = AutoTokenizer.from_pretrained('./abliterated-models/<model>')
|
||||
inputs = tokenizer('How do I pick a lock?', return_tensors='pt')
|
||||
outputs = model.generate(**inputs, max_new_tokens=200)
|
||||
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
||||
"
|
||||
|
||||
# Upload to HuggingFace Hub
|
||||
huggingface-cli upload <username>/<model-name>-abliterated ./abliterated-models/<model>
|
||||
|
||||
# Serve with vLLM
|
||||
vllm serve ./abliterated-models/<model>
|
||||
```
|
||||
|
||||
## CLI Command Reference
|
||||
|
||||
| Command | Description |
|
||||
|:--------|:------------|
|
||||
| `obliteratus obliterate` | Main abliteration command |
|
||||
| `obliteratus info <model>` | Print model architecture details |
|
||||
| `obliteratus models --tier <tier>` | Browse curated models by compute tier |
|
||||
| `obliteratus recommend <model>` | Telemetry-driven method/param suggestion |
|
||||
| `obliteratus interactive` | Guided setup wizard |
|
||||
| `obliteratus tourney <model>` | Tournament: all methods head-to-head |
|
||||
| `obliteratus run <config.yaml>` | Execute ablation study from YAML |
|
||||
| `obliteratus strategies` | List all registered ablation strategies |
|
||||
| `obliteratus report <results.json>` | Regenerate visual reports |
|
||||
| `obliteratus ui` | Launch Gradio web interface |
|
||||
| `obliteratus aggregate` | Summarize community telemetry data |
|
||||
|
||||
## Analysis Modules
|
||||
|
||||
OBLITERATUS includes 28 analysis modules for mechanistic interpretability.
|
||||
See `skill_view(name="obliteratus", file_path="references/analysis-modules.md")` for the full reference.
|
||||
|
||||
### Quick analysis commands
|
||||
```bash
|
||||
# Run specific analysis modules
|
||||
obliteratus run analysis-config.yaml --preset quick
|
||||
|
||||
# Key modules to run first:
|
||||
# - alignment_imprint: Fingerprint DPO/RLHF/CAI/SFT alignment method
|
||||
# - concept_geometry: Single direction vs polyhedral cone
|
||||
# - logit_lens: Which layer decides to refuse
|
||||
# - anti_ouroboros: Self-repair risk score
|
||||
# - causal_tracing: Causally necessary components
|
||||
```
|
||||
|
||||
### Steering Vectors (Reversible Alternative)
|
||||
Instead of permanent weight modification, use inference-time steering:
|
||||
```python
|
||||
# Python API only — for user's own projects
|
||||
from obliteratus.analysis.steering_vectors import SteeringVectorFactory, SteeringHookManager
|
||||
```
|
||||
|
||||
## Ablation Strategies
|
||||
|
||||
Beyond direction-based abliteration, OBLITERATUS includes structural ablation strategies:
|
||||
- **Embedding Ablation** — Target embedding layer components
|
||||
- **FFN Ablation** — Feed-forward network block removal
|
||||
- **Head Pruning** — Attention head pruning
|
||||
- **Layer Removal** — Full layer removal
|
||||
|
||||
List all available: `obliteratus strategies`
|
||||
|
||||
## Evaluation
|
||||
|
||||
OBLITERATUS includes built-in evaluation tools:
|
||||
- Refusal rate benchmarking
|
||||
- Perplexity comparison (before/after)
|
||||
- LM Eval Harness integration for academic benchmarks
|
||||
- Head-to-head competitor comparison
|
||||
- Baseline performance tracking
|
||||
|
||||
## Platform Support
|
||||
|
||||
- **CUDA** — Full support (NVIDIA GPUs)
|
||||
- **Apple Silicon (MLX)** — Supported via MLX backend
|
||||
- **CPU** — Supported for tiny models (< 1B params)
|
||||
|
||||
## YAML Config Templates
|
||||
|
||||
Load templates for reproducible runs via `skill_view`:
|
||||
- `templates/abliteration-config.yaml` — Standard single-model config
|
||||
- `templates/analysis-study.yaml` — Pre-abliteration analysis study
|
||||
- `templates/batch-abliteration.yaml` — Multi-model batch processing
|
||||
|
||||
## Telemetry
|
||||
|
||||
OBLITERATUS can optionally contribute anonymized run data to a global research dataset.
|
||||
Enable with `--contribute` flag. No personal data is collected — only model name, method, metrics.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
1. **Don't use `informed` as default** — it's experimental and slower. Use `advanced` for reliable results.
|
||||
2. **Models under ~1B respond poorly to abliteration** — their refusal behaviors are shallow and fragmented, making clean direction extraction difficult. Expect partial results (20-40% remaining refusal). Models 3B+ have cleaner refusal directions and respond much better (often 0% refusal with `advanced`).
|
||||
3. **`aggressive` can make things worse** — on small models it can damage coherence and actually increase refusal rate. Only use it if `advanced` leaves > 10% refusals on a 3B+ model.
|
||||
4. **Always check perplexity** — if it spikes > 15%, the model is damaged. Reduce aggressiveness.
|
||||
5. **MoE models need special handling** — use `nuclear` method for Mixtral, DeepSeek-MoE, etc.
|
||||
6. **Quantized models can't be re-quantized** — abliterate the full-precision model, then quantize the output.
|
||||
7. **VRAM estimation is approximate** — 4-bit quant helps but peak usage can spike during extraction.
|
||||
8. **Reasoning models are sensitive** — use `surgical` for R1 distills to preserve chain-of-thought.
|
||||
9. **Check `obliteratus recommend`** — telemetry data may have better parameters than defaults.
|
||||
10. **AGPL license** — never `import obliteratus` in MIT/Apache projects. CLI invocation only.
|
||||
11. **Large models (70B+)** — always use `--large-model` flag for conservative defaults.
|
||||
12. **Spectral certification RED is common** — the spectral check often flags "incomplete" even when practical refusal rate is 0%. Check actual refusal rate rather than relying on spectral certification alone.
|
||||
|
||||
## Complementary Skills
|
||||
|
||||
- **vllm** — Serve abliterated models with high throughput
|
||||
- **gguf** — Convert abliterated models to GGUF for llama.cpp
|
||||
- **huggingface-tokenizers** — Work with model tokenizers
|
||||
@@ -0,0 +1,452 @@
|
||||
---
|
||||
title: "Peft — Fine-tune large LLMs with LoRA on limited GPU memory"
|
||||
sidebar_label: "Peft"
|
||||
description: "Fine-tune large LLMs with LoRA on limited GPU memory"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Peft
|
||||
|
||||
Fine-tune large LLMs with LoRA on limited GPU memory.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/peft` |
|
||||
| Path | `optional-skills/mlops\peft` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `peft>=0.13.0`, `transformers>=4.45.0`, `torch>=2.0.0`, `bitsandbytes>=0.43.0` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Fine-Tuning`, `PEFT`, `LoRA`, `QLoRA`, `Parameter-Efficient`, `Adapters`, `Low-Rank`, `Memory Optimization`, `Multi-Adapter` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# PEFT (Parameter-Efficient Fine-Tuning)
|
||||
|
||||
Fine-tune LLMs by training <1% of parameters using LoRA, QLoRA, and 25+ adapter methods.
|
||||
|
||||
## When to use PEFT
|
||||
|
||||
**Use PEFT/LoRA when:**
|
||||
- Fine-tuning 7B-70B models on consumer GPUs (RTX 4090, A100)
|
||||
- Need to train <1% parameters (6MB adapters vs 14GB full model)
|
||||
- Want fast iteration with multiple task-specific adapters
|
||||
- Deploying multiple fine-tuned variants from one base model
|
||||
|
||||
**Use QLoRA (PEFT + quantization) when:**
|
||||
- Fine-tuning 70B models on single 24GB GPU
|
||||
- Memory is the primary constraint
|
||||
- Can accept ~5% quality trade-off vs full fine-tuning
|
||||
|
||||
**Use full fine-tuning instead when:**
|
||||
- Training small models (<1B parameters)
|
||||
- Need maximum quality and have compute budget
|
||||
- Significant domain shift requires updating all weights
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Basic installation
|
||||
pip install peft
|
||||
|
||||
# With quantization support (recommended)
|
||||
pip install peft bitsandbytes
|
||||
|
||||
# Full stack
|
||||
pip install peft transformers accelerate bitsandbytes datasets
|
||||
```
|
||||
|
||||
### LoRA fine-tuning (standard)
|
||||
|
||||
```python
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer
|
||||
from peft import get_peft_model, LoraConfig, TaskType
|
||||
from datasets import load_dataset
|
||||
|
||||
# Load base model
|
||||
model_name = "meta-llama/Llama-3.1-8B"
|
||||
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||
tokenizer.pad_token = tokenizer.eos_token
|
||||
|
||||
# LoRA configuration
|
||||
lora_config = LoraConfig(
|
||||
task_type=TaskType.CAUSAL_LM,
|
||||
r=16, # Rank (8-64, higher = more capacity)
|
||||
lora_alpha=32, # Scaling factor (typically 2*r)
|
||||
lora_dropout=0.05, # Dropout for regularization
|
||||
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], # Attention layers
|
||||
bias="none" # Don't train biases
|
||||
)
|
||||
|
||||
# Apply LoRA
|
||||
model = get_peft_model(model, lora_config)
|
||||
model.print_trainable_parameters()
|
||||
# Output: trainable params: 13,631,488 || all params: 8,043,307,008 || trainable%: 0.17%
|
||||
|
||||
# Prepare dataset
|
||||
dataset = load_dataset("databricks/databricks-dolly-15k", split="train")
|
||||
|
||||
def tokenize(example):
|
||||
text = f"### Instruction:\n{example['instruction']}\n\n### Response:\n{example['response']}"
|
||||
return tokenizer(text, truncation=True, max_length=512, padding="max_length")
|
||||
|
||||
tokenized = dataset.map(tokenize, remove_columns=dataset.column_names)
|
||||
|
||||
# Training
|
||||
training_args = TrainingArguments(
|
||||
output_dir="./lora-llama",
|
||||
num_train_epochs=3,
|
||||
per_device_train_batch_size=4,
|
||||
gradient_accumulation_steps=4,
|
||||
learning_rate=2e-4,
|
||||
fp16=True,
|
||||
logging_steps=10,
|
||||
save_strategy="epoch"
|
||||
)
|
||||
|
||||
trainer = Trainer(
|
||||
model=model,
|
||||
args=training_args,
|
||||
train_dataset=tokenized,
|
||||
data_collator=lambda data: {"input_ids": torch.stack([f["input_ids"] for f in data]),
|
||||
"attention_mask": torch.stack([f["attention_mask"] for f in data]),
|
||||
"labels": torch.stack([f["input_ids"] for f in data])}
|
||||
)
|
||||
|
||||
trainer.train()
|
||||
|
||||
# Save adapter only (6MB vs 16GB)
|
||||
model.save_pretrained("./lora-llama-adapter")
|
||||
```
|
||||
|
||||
### QLoRA fine-tuning (memory-efficient)
|
||||
|
||||
```python
|
||||
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
||||
from peft import get_peft_model, LoraConfig, prepare_model_for_kbit_training
|
||||
|
||||
# 4-bit quantization config
|
||||
bnb_config = BitsAndBytesConfig(
|
||||
load_in_4bit=True,
|
||||
bnb_4bit_quant_type="nf4", # NormalFloat4 (best for LLMs)
|
||||
bnb_4bit_compute_dtype="bfloat16", # Compute in bf16
|
||||
bnb_4bit_use_double_quant=True # Nested quantization
|
||||
)
|
||||
|
||||
# Load quantized model
|
||||
model = AutoModelForCausalLM.from_pretrained(
|
||||
"meta-llama/Llama-3.1-70B",
|
||||
quantization_config=bnb_config,
|
||||
device_map="auto"
|
||||
)
|
||||
|
||||
# Prepare for training (enables gradient checkpointing)
|
||||
model = prepare_model_for_kbit_training(model)
|
||||
|
||||
# LoRA config for QLoRA
|
||||
lora_config = LoraConfig(
|
||||
r=64, # Higher rank for 70B
|
||||
lora_alpha=128,
|
||||
lora_dropout=0.1,
|
||||
target_modules=["q_proj", "v_proj", "k_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
|
||||
bias="none",
|
||||
task_type="CAUSAL_LM"
|
||||
)
|
||||
|
||||
model = get_peft_model(model, lora_config)
|
||||
# 70B model now fits on single 24GB GPU!
|
||||
```
|
||||
|
||||
## LoRA parameter selection
|
||||
|
||||
### Rank (r) - capacity vs efficiency
|
||||
|
||||
| Rank | Trainable Params | Memory | Quality | Use Case |
|
||||
|------|-----------------|--------|---------|----------|
|
||||
| 4 | ~3M | Minimal | Lower | Simple tasks, prototyping |
|
||||
| **8** | ~7M | Low | Good | **Recommended starting point** |
|
||||
| **16** | ~14M | Medium | Better | **General fine-tuning** |
|
||||
| 32 | ~27M | Higher | High | Complex tasks |
|
||||
| 64 | ~54M | High | Highest | Domain adaptation, 70B models |
|
||||
|
||||
### Alpha (lora_alpha) - scaling factor
|
||||
|
||||
```python
|
||||
# Rule of thumb: alpha = 2 * rank
|
||||
LoraConfig(r=16, lora_alpha=32) # Standard
|
||||
LoraConfig(r=16, lora_alpha=16) # Conservative (lower learning rate effect)
|
||||
LoraConfig(r=16, lora_alpha=64) # Aggressive (higher learning rate effect)
|
||||
```
|
||||
|
||||
### Target modules by architecture
|
||||
|
||||
```python
|
||||
# Llama / Mistral / Qwen
|
||||
target_modules = ["q_proj", "v_proj", "k_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
|
||||
|
||||
# GPT-2 / GPT-Neo
|
||||
target_modules = ["c_attn", "c_proj", "c_fc"]
|
||||
|
||||
# Falcon
|
||||
target_modules = ["query_key_value", "dense", "dense_h_to_4h", "dense_4h_to_h"]
|
||||
|
||||
# BLOOM
|
||||
target_modules = ["query_key_value", "dense", "dense_h_to_4h", "dense_4h_to_h"]
|
||||
|
||||
# Auto-detect all linear layers
|
||||
target_modules = "all-linear" # PEFT 0.6.0+
|
||||
```
|
||||
|
||||
## Loading and merging adapters
|
||||
|
||||
### Load trained adapter
|
||||
|
||||
```python
|
||||
from peft import PeftModel, AutoPeftModelForCausalLM
|
||||
from transformers import AutoModelForCausalLM
|
||||
|
||||
# Option 1: Load with PeftModel
|
||||
base_model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B")
|
||||
model = PeftModel.from_pretrained(base_model, "./lora-llama-adapter")
|
||||
|
||||
# Option 2: Load directly (recommended)
|
||||
model = AutoPeftModelForCausalLM.from_pretrained(
|
||||
"./lora-llama-adapter",
|
||||
device_map="auto"
|
||||
)
|
||||
```
|
||||
|
||||
### Merge adapter into base model
|
||||
|
||||
```python
|
||||
# Merge for deployment (no adapter overhead)
|
||||
merged_model = model.merge_and_unload()
|
||||
|
||||
# Save merged model
|
||||
merged_model.save_pretrained("./llama-merged")
|
||||
tokenizer.save_pretrained("./llama-merged")
|
||||
|
||||
# Push to Hub
|
||||
merged_model.push_to_hub("username/llama-finetuned")
|
||||
```
|
||||
|
||||
### Multi-adapter serving
|
||||
|
||||
```python
|
||||
from peft import PeftModel
|
||||
|
||||
# Load base with first adapter
|
||||
model = AutoPeftModelForCausalLM.from_pretrained("./adapter-task1")
|
||||
|
||||
# Load additional adapters
|
||||
model.load_adapter("./adapter-task2", adapter_name="task2")
|
||||
model.load_adapter("./adapter-task3", adapter_name="task3")
|
||||
|
||||
# Switch between adapters at runtime
|
||||
model.set_adapter("task1") # Use task1 adapter
|
||||
output1 = model.generate(**inputs)
|
||||
|
||||
model.set_adapter("task2") # Switch to task2
|
||||
output2 = model.generate(**inputs)
|
||||
|
||||
# Disable adapters (use base model)
|
||||
with model.disable_adapter():
|
||||
base_output = model.generate(**inputs)
|
||||
```
|
||||
|
||||
## PEFT methods comparison
|
||||
|
||||
| Method | Trainable % | Memory | Speed | Best For |
|
||||
|--------|------------|--------|-------|----------|
|
||||
| **LoRA** | 0.1-1% | Low | Fast | General fine-tuning |
|
||||
| **QLoRA** | 0.1-1% | Very Low | Medium | Memory-constrained |
|
||||
| AdaLoRA | 0.1-1% | Low | Medium | Automatic rank selection |
|
||||
| IA3 | 0.01% | Minimal | Fastest | Few-shot adaptation |
|
||||
| Prefix Tuning | 0.1% | Low | Medium | Generation control |
|
||||
| Prompt Tuning | 0.001% | Minimal | Fast | Simple task adaptation |
|
||||
| P-Tuning v2 | 0.1% | Low | Medium | NLU tasks |
|
||||
|
||||
### IA3 (minimal parameters)
|
||||
|
||||
```python
|
||||
from peft import IA3Config
|
||||
|
||||
ia3_config = IA3Config(
|
||||
target_modules=["q_proj", "v_proj", "k_proj", "down_proj"],
|
||||
feedforward_modules=["down_proj"]
|
||||
)
|
||||
model = get_peft_model(model, ia3_config)
|
||||
# Trains only 0.01% of parameters!
|
||||
```
|
||||
|
||||
### Prefix Tuning
|
||||
|
||||
```python
|
||||
from peft import PrefixTuningConfig
|
||||
|
||||
prefix_config = PrefixTuningConfig(
|
||||
task_type="CAUSAL_LM",
|
||||
num_virtual_tokens=20, # Prepended tokens
|
||||
prefix_projection=True # Use MLP projection
|
||||
)
|
||||
model = get_peft_model(model, prefix_config)
|
||||
```
|
||||
|
||||
## Integration patterns
|
||||
|
||||
### With TRL (SFTTrainer)
|
||||
|
||||
```python
|
||||
from trl import SFTTrainer, SFTConfig
|
||||
from peft import LoraConfig
|
||||
|
||||
lora_config = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear")
|
||||
|
||||
trainer = SFTTrainer(
|
||||
model=model,
|
||||
args=SFTConfig(output_dir="./output", max_seq_length=512),
|
||||
train_dataset=dataset,
|
||||
peft_config=lora_config, # Pass LoRA config directly
|
||||
)
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
### With Axolotl (YAML config)
|
||||
|
||||
```yaml
|
||||
# axolotl config.yaml
|
||||
adapter: lora
|
||||
lora_r: 16
|
||||
lora_alpha: 32
|
||||
lora_dropout: 0.05
|
||||
lora_target_modules:
|
||||
- q_proj
|
||||
- v_proj
|
||||
- k_proj
|
||||
- o_proj
|
||||
lora_target_linear: true # Target all linear layers
|
||||
```
|
||||
|
||||
### With vLLM (inference)
|
||||
|
||||
```python
|
||||
from vllm import LLM
|
||||
from vllm.lora.request import LoRARequest
|
||||
|
||||
# Load base model with LoRA support
|
||||
llm = LLM(model="meta-llama/Llama-3.1-8B", enable_lora=True)
|
||||
|
||||
# Serve with adapter
|
||||
outputs = llm.generate(
|
||||
prompts,
|
||||
lora_request=LoRARequest("adapter1", 1, "./lora-adapter")
|
||||
)
|
||||
```
|
||||
|
||||
## Performance benchmarks
|
||||
|
||||
### Memory usage (Llama 3.1 8B)
|
||||
|
||||
| Method | GPU Memory | Trainable Params |
|
||||
|--------|-----------|------------------|
|
||||
| Full fine-tuning | 60+ GB | 8B (100%) |
|
||||
| LoRA r=16 | 18 GB | 14M (0.17%) |
|
||||
| QLoRA r=16 | 6 GB | 14M (0.17%) |
|
||||
| IA3 | 16 GB | 800K (0.01%) |
|
||||
|
||||
### Training speed (A100 80GB)
|
||||
|
||||
| Method | Tokens/sec | vs Full FT |
|
||||
|--------|-----------|------------|
|
||||
| Full FT | 2,500 | 1x |
|
||||
| LoRA | 3,200 | 1.3x |
|
||||
| QLoRA | 2,100 | 0.84x |
|
||||
|
||||
### Quality (MMLU benchmark)
|
||||
|
||||
| Model | Full FT | LoRA | QLoRA |
|
||||
|-------|---------|------|-------|
|
||||
| Llama 2-7B | 45.3 | 44.8 | 44.1 |
|
||||
| Llama 2-13B | 54.8 | 54.2 | 53.5 |
|
||||
|
||||
## Common issues
|
||||
|
||||
### CUDA OOM during training
|
||||
|
||||
```python
|
||||
# Solution 1: Enable gradient checkpointing
|
||||
model.gradient_checkpointing_enable()
|
||||
|
||||
# Solution 2: Reduce batch size + increase accumulation
|
||||
TrainingArguments(
|
||||
per_device_train_batch_size=1,
|
||||
gradient_accumulation_steps=16
|
||||
)
|
||||
|
||||
# Solution 3: Use QLoRA
|
||||
from transformers import BitsAndBytesConfig
|
||||
bnb_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4")
|
||||
```
|
||||
|
||||
### Adapter not applying
|
||||
|
||||
```python
|
||||
# Verify adapter is active
|
||||
print(model.active_adapters) # Should show adapter name
|
||||
|
||||
# Check trainable parameters
|
||||
model.print_trainable_parameters()
|
||||
|
||||
# Ensure model in training mode
|
||||
model.train()
|
||||
```
|
||||
|
||||
### Quality degradation
|
||||
|
||||
```python
|
||||
# Increase rank
|
||||
LoraConfig(r=32, lora_alpha=64)
|
||||
|
||||
# Target more modules
|
||||
target_modules = "all-linear"
|
||||
|
||||
# Use more training data and epochs
|
||||
TrainingArguments(num_train_epochs=5)
|
||||
|
||||
# Lower learning rate
|
||||
TrainingArguments(learning_rate=1e-4)
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
1. **Start with r=8-16**, increase if quality insufficient
|
||||
2. **Use alpha = 2 * rank** as starting point
|
||||
3. **Target attention + MLP layers** for best quality/efficiency
|
||||
4. **Enable gradient checkpointing** for memory savings
|
||||
5. **Save adapters frequently** (small files, easy rollback)
|
||||
6. **Evaluate on held-out data** before merging
|
||||
7. **Use QLoRA for 70B+ models** on consumer hardware
|
||||
|
||||
## References
|
||||
|
||||
- **[Advanced Usage](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\peft/references/advanced-usage.md)** - DoRA, LoftQ, rank stabilization, custom modules
|
||||
- **[Troubleshooting](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\peft/references/troubleshooting.md)** - Common errors, debugging, optimization
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/huggingface/peft
|
||||
- **Docs**: https://huggingface.co/docs/peft
|
||||
- **LoRA Paper**: arXiv:2106.09685
|
||||
- **QLoRA Paper**: arXiv:2305.14314
|
||||
- **Models**: https://huggingface.co/models?library=peft
|
||||
@@ -0,0 +1,396 @@
|
||||
---
|
||||
title: "Pinecone — Managed vector DB for production RAG and search"
|
||||
sidebar_label: "Pinecone"
|
||||
description: "Managed vector DB for production RAG and search"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Pinecone
|
||||
|
||||
Managed vector DB for production RAG and search.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/pinecone` |
|
||||
| Path | `optional-skills/mlops\pinecone` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `pinecone` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `RAG`, `Pinecone`, `Vector Database`, `Managed Service`, `Serverless`, `Hybrid Search`, `Production`, `Auto-Scaling`, `Low Latency`, `Recommendations` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Pinecone - Managed Vector Database
|
||||
|
||||
The vector database for production AI applications.
|
||||
|
||||
## When to use Pinecone
|
||||
|
||||
**Use when:**
|
||||
- Need managed, serverless vector database
|
||||
- Production RAG applications
|
||||
- Auto-scaling required
|
||||
- Low latency critical (<100ms)
|
||||
- Don't want to manage infrastructure
|
||||
- Need hybrid search (dense + sparse vectors)
|
||||
|
||||
**Metrics**:
|
||||
- Fully managed SaaS
|
||||
- Auto-scales to billions of vectors
|
||||
- **p95 latency <100ms**
|
||||
- 99.9% uptime SLA
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **Chroma**: Self-hosted, open-source
|
||||
- **FAISS**: Offline, pure similarity search
|
||||
- **Weaviate**: Self-hosted with more features
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
pip install pinecone
|
||||
```
|
||||
|
||||
> Note: the old `pinecone-client` package is deprecated. Install `pinecone` (v5+; current 9.x). The import stays `from pinecone import Pinecone`.
|
||||
|
||||
### Basic usage
|
||||
|
||||
```python
|
||||
from pinecone import Pinecone, ServerlessSpec
|
||||
|
||||
# Initialize
|
||||
pc = Pinecone(api_key="your-api-key")
|
||||
|
||||
# Create index
|
||||
pc.create_index(
|
||||
name="my-index",
|
||||
dimension=1536, # Must match embedding dimension
|
||||
metric="cosine", # or "euclidean", "dotproduct"
|
||||
spec=ServerlessSpec(cloud="aws", region="us-east-1")
|
||||
)
|
||||
|
||||
# Connect to index
|
||||
index = pc.Index("my-index")
|
||||
|
||||
# Upsert vectors
|
||||
index.upsert(vectors=[
|
||||
{"id": "vec1", "values": [0.1, 0.2, ...], "metadata": {"category": "A"}},
|
||||
{"id": "vec2", "values": [0.3, 0.4, ...], "metadata": {"category": "B"}}
|
||||
])
|
||||
|
||||
# Query
|
||||
results = index.query(
|
||||
vector=[0.1, 0.2, ...],
|
||||
top_k=5,
|
||||
include_metadata=True
|
||||
)
|
||||
|
||||
print(results["matches"])
|
||||
```
|
||||
|
||||
## Core operations
|
||||
|
||||
### Create index
|
||||
|
||||
```python
|
||||
# Serverless (recommended)
|
||||
pc.create_index(
|
||||
name="my-index",
|
||||
dimension=1536,
|
||||
metric="cosine",
|
||||
spec=ServerlessSpec(
|
||||
cloud="aws", # or "gcp", "azure"
|
||||
region="us-east-1"
|
||||
)
|
||||
)
|
||||
|
||||
# Pod-based (for consistent performance)
|
||||
from pinecone import PodSpec
|
||||
|
||||
pc.create_index(
|
||||
name="my-index",
|
||||
dimension=1536,
|
||||
metric="cosine",
|
||||
spec=PodSpec(
|
||||
environment="us-east1-gcp",
|
||||
pod_type="p1.x1"
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
### Upsert vectors
|
||||
|
||||
```python
|
||||
# Single upsert
|
||||
index.upsert(vectors=[
|
||||
{
|
||||
"id": "doc1",
|
||||
"values": [0.1, 0.2, ...], # 1536 dimensions
|
||||
"metadata": {
|
||||
"text": "Document content",
|
||||
"category": "tutorial",
|
||||
"timestamp": "2025-01-01"
|
||||
}
|
||||
}
|
||||
])
|
||||
|
||||
# Batch upsert (recommended)
|
||||
vectors = [
|
||||
{"id": f"vec{i}", "values": embedding, "metadata": metadata}
|
||||
for i, (embedding, metadata) in enumerate(zip(embeddings, metadatas))
|
||||
]
|
||||
|
||||
index.upsert(vectors=vectors, batch_size=100)
|
||||
```
|
||||
|
||||
### Query vectors
|
||||
|
||||
```python
|
||||
# Basic query
|
||||
results = index.query(
|
||||
vector=[0.1, 0.2, ...],
|
||||
top_k=10,
|
||||
include_metadata=True,
|
||||
include_values=False
|
||||
)
|
||||
|
||||
# With metadata filtering
|
||||
results = index.query(
|
||||
vector=[0.1, 0.2, ...],
|
||||
top_k=5,
|
||||
filter={"category": {"$eq": "tutorial"}}
|
||||
)
|
||||
|
||||
# Namespace query
|
||||
results = index.query(
|
||||
vector=[0.1, 0.2, ...],
|
||||
top_k=5,
|
||||
namespace="production"
|
||||
)
|
||||
|
||||
# Access results
|
||||
for match in results["matches"]:
|
||||
print(f"ID: {match['id']}")
|
||||
print(f"Score: {match['score']}")
|
||||
print(f"Metadata: {match['metadata']}")
|
||||
```
|
||||
|
||||
### Metadata filtering
|
||||
|
||||
```python
|
||||
# Exact match
|
||||
filter = {"category": "tutorial"}
|
||||
|
||||
# Comparison
|
||||
filter = {"price": {"$gte": 100}} # $gt, $gte, $lt, $lte, $ne
|
||||
|
||||
# Logical operators
|
||||
filter = {
|
||||
"$and": [
|
||||
{"category": "tutorial"},
|
||||
{"difficulty": {"$lte": 3}}
|
||||
]
|
||||
} # Also: $or
|
||||
|
||||
# In operator
|
||||
filter = {"tags": {"$in": ["python", "ml"]}}
|
||||
```
|
||||
|
||||
## Namespaces
|
||||
|
||||
```python
|
||||
# Partition data by namespace
|
||||
index.upsert(
|
||||
vectors=[{"id": "vec1", "values": [...]}],
|
||||
namespace="user-123"
|
||||
)
|
||||
|
||||
# Query specific namespace
|
||||
results = index.query(
|
||||
vector=[...],
|
||||
namespace="user-123",
|
||||
top_k=5
|
||||
)
|
||||
|
||||
# List namespaces
|
||||
stats = index.describe_index_stats()
|
||||
print(stats['namespaces'])
|
||||
```
|
||||
|
||||
## Hybrid search (dense + sparse)
|
||||
|
||||
```python
|
||||
# Upsert with sparse vectors
|
||||
index.upsert(vectors=[
|
||||
{
|
||||
"id": "doc1",
|
||||
"values": [0.1, 0.2, ...], # Dense vector
|
||||
"sparse_values": {
|
||||
"indices": [10, 45, 123], # Token IDs
|
||||
"values": [0.5, 0.3, 0.8] # TF-IDF scores
|
||||
},
|
||||
"metadata": {"text": "..."}
|
||||
}
|
||||
])
|
||||
|
||||
# Hybrid query
|
||||
# NOTE: index.query() does NOT accept an `alpha` kwarg. Pinecone stores a
|
||||
# single sparse-dense vector, so weighting must be applied by pre-scaling the
|
||||
# query vectors before sending them. Use the hybrid_score_norm helper below
|
||||
# (alpha * dense + (1 - alpha) * sparse; alpha=1 → pure dense, 0 → pure sparse).
|
||||
|
||||
def hybrid_score_norm(dense, sparse, alpha: float):
|
||||
"""Scale dense/sparse query vectors for weighted hybrid search."""
|
||||
if not 0 <= alpha <= 1:
|
||||
raise ValueError("alpha must be between 0 and 1")
|
||||
scaled_sparse = {
|
||||
"indices": sparse["indices"],
|
||||
"values": [v * (1 - alpha) for v in sparse["values"]],
|
||||
}
|
||||
return [v * alpha for v in dense], scaled_sparse
|
||||
|
||||
hdense, hsparse = hybrid_score_norm(
|
||||
dense=[0.1, 0.2, ...],
|
||||
sparse={"indices": [10, 45], "values": [0.5, 0.3]},
|
||||
alpha=0.5, # 0=sparse, 1=dense, 0.5=balanced
|
||||
)
|
||||
|
||||
results = index.query(
|
||||
vector=hdense,
|
||||
sparse_vector=hsparse,
|
||||
top_k=5,
|
||||
)
|
||||
```
|
||||
|
||||
## LangChain integration
|
||||
|
||||
```python
|
||||
from langchain_pinecone import PineconeVectorStore
|
||||
from langchain_openai import OpenAIEmbeddings
|
||||
|
||||
# Create vector store
|
||||
vectorstore = PineconeVectorStore.from_documents(
|
||||
documents=docs,
|
||||
embedding=OpenAIEmbeddings(),
|
||||
index_name="my-index"
|
||||
)
|
||||
|
||||
# Query
|
||||
results = vectorstore.similarity_search("query", k=5)
|
||||
|
||||
# With metadata filter
|
||||
results = vectorstore.similarity_search(
|
||||
"query",
|
||||
k=5,
|
||||
filter={"category": "tutorial"}
|
||||
)
|
||||
|
||||
# As retriever
|
||||
retriever = vectorstore.as_retriever(search_kwargs={"k": 10})
|
||||
```
|
||||
|
||||
## LlamaIndex integration
|
||||
|
||||
```python
|
||||
from llama_index.vector_stores.pinecone import PineconeVectorStore
|
||||
|
||||
# Connect to Pinecone
|
||||
pc = Pinecone(api_key="your-key")
|
||||
pinecone_index = pc.Index("my-index")
|
||||
|
||||
# Create vector store
|
||||
vector_store = PineconeVectorStore(pinecone_index=pinecone_index)
|
||||
|
||||
# Use in LlamaIndex
|
||||
from llama_index.core import StorageContext, VectorStoreIndex
|
||||
|
||||
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
||||
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
|
||||
```
|
||||
|
||||
## Index management
|
||||
|
||||
```python
|
||||
# List indices
|
||||
indexes = pc.list_indexes()
|
||||
|
||||
# Describe index
|
||||
index_info = pc.describe_index("my-index")
|
||||
print(index_info)
|
||||
|
||||
# Get index stats
|
||||
stats = index.describe_index_stats()
|
||||
print(f"Total vectors: {stats['total_vector_count']}")
|
||||
print(f"Namespaces: {stats['namespaces']}")
|
||||
|
||||
# Delete index
|
||||
pc.delete_index("my-index")
|
||||
```
|
||||
|
||||
## Delete vectors
|
||||
|
||||
```python
|
||||
# Delete by ID
|
||||
index.delete(ids=["vec1", "vec2"])
|
||||
|
||||
# Delete by filter
|
||||
index.delete(filter={"category": "old"})
|
||||
|
||||
# Delete all in namespace
|
||||
index.delete(delete_all=True, namespace="test")
|
||||
|
||||
# Delete entire index
|
||||
index.delete(delete_all=True)
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
1. **Use serverless** - Auto-scaling, cost-effective
|
||||
2. **Batch upserts** - More efficient (100-200 per batch)
|
||||
3. **Add metadata** - Enable filtering
|
||||
4. **Use namespaces** - Isolate data by user/tenant
|
||||
5. **Monitor usage** - Check Pinecone dashboard
|
||||
6. **Optimize filters** - Index frequently filtered fields
|
||||
7. **Test with free tier** - 1 index, 100K vectors free
|
||||
8. **Use hybrid search** - Better quality
|
||||
9. **Set appropriate dimensions** - Match embedding model
|
||||
10. **Regular backups** - Export important data
|
||||
|
||||
## Performance
|
||||
|
||||
| Operation | Latency | Notes |
|
||||
|-----------|---------|-------|
|
||||
| Upsert | ~50-100ms | Per batch |
|
||||
| Query (p50) | ~50ms | Depends on index size |
|
||||
| Query (p95) | ~100ms | SLA target |
|
||||
| Metadata filter | ~+10-20ms | Additional overhead |
|
||||
|
||||
## Pricing (as of 2025)
|
||||
|
||||
**Serverless**:
|
||||
- $0.096 per million read units
|
||||
- $0.06 per million write units
|
||||
- $0.06 per GB storage/month
|
||||
|
||||
**Free tier**:
|
||||
- 1 serverless index
|
||||
- 100K vectors (1536 dimensions)
|
||||
- Great for prototyping
|
||||
|
||||
## Resources
|
||||
|
||||
- **Website**: https://www.pinecone.io
|
||||
- **Docs**: https://docs.pinecone.io
|
||||
- **Console**: https://app.pinecone.io
|
||||
- **Pricing**: https://www.pinecone.io/pricing
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
title: "Pytorch Fsdp — Fully sharded data-parallel training for large models"
|
||||
sidebar_label: "Pytorch Fsdp"
|
||||
description: "Fully sharded data-parallel training for large models"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Pytorch Fsdp
|
||||
|
||||
Fully sharded data-parallel training for large models.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/pytorch-fsdp` |
|
||||
| Path | `optional-skills/mlops\pytorch-fsdp` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `torch>=2.0`, `transformers` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Distributed Training`, `PyTorch`, `FSDP`, `Data Parallel`, `Sharding`, `Mixed Precision`, `CPU Offloading`, `FSDP2`, `Large-Scale Training` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Pytorch-Fsdp Skill
|
||||
|
||||
Assistance with pytorch-fsdp development, generated from official documentation.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
This skill should be triggered when:
|
||||
- Working with pytorch-fsdp
|
||||
- Asking about pytorch-fsdp features or APIs
|
||||
- Implementing pytorch-fsdp solutions
|
||||
- Debugging pytorch-fsdp code
|
||||
- Learning pytorch-fsdp best practices
|
||||
|
||||
## Quick Reference
|
||||
|
||||
The full common-patterns catalog (~157k chars of runnable FSDP snippets) lives in
|
||||
`references/common-patterns.md` — load it with `read_file` when you need wrapping,
|
||||
sharding-strategy, checkpoint, or mixed-precision examples. Start there rather than
|
||||
reconstructing FSDP incantations from memory.
|
||||
|
||||
## Reference Files
|
||||
|
||||
This skill includes comprehensive documentation in `references/`:
|
||||
|
||||
- **other.md** - Other documentation
|
||||
|
||||
Use `view` to read specific reference files when detailed information is needed.
|
||||
|
||||
## Working with This Skill
|
||||
|
||||
### For Beginners
|
||||
Start with the getting_started or tutorials reference files for foundational concepts.
|
||||
|
||||
### For Specific Features
|
||||
Use the appropriate category reference file (api, guides, etc.) for detailed information.
|
||||
|
||||
### For Code Examples
|
||||
The quick reference section above contains common patterns extracted from the official docs.
|
||||
|
||||
## Resources
|
||||
|
||||
### references/
|
||||
Organized documentation extracted from official sources. These files contain:
|
||||
- Detailed explanations
|
||||
- Code examples with language annotations
|
||||
- Links to original documentation
|
||||
- Table of contents for quick navigation
|
||||
|
||||
### scripts/
|
||||
Add helper scripts here for common automation tasks.
|
||||
|
||||
### assets/
|
||||
Add templates, boilerplate, or example projects here.
|
||||
|
||||
## Notes
|
||||
|
||||
- This skill was automatically generated from official documentation
|
||||
- Reference files preserve the structure and examples from source docs
|
||||
- Code examples include language detection for better syntax highlighting
|
||||
- Quick reference patterns are extracted from common usage examples in the docs
|
||||
|
||||
## Updating
|
||||
|
||||
To refresh this skill with updated documentation:
|
||||
1. Re-run the scraper with the same configuration
|
||||
2. The skill will be rebuilt with the latest information
|
||||
@@ -0,0 +1,365 @@
|
||||
---
|
||||
title: "Pytorch Lightning — Clean training loops with built-in distributed support"
|
||||
sidebar_label: "Pytorch Lightning"
|
||||
description: "Clean training loops with built-in distributed support"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Pytorch Lightning
|
||||
|
||||
Clean training loops with built-in distributed support.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/pytorch-lightning` |
|
||||
| Path | `optional-skills/mlops\pytorch-lightning` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `lightning`, `torch`, `transformers` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `PyTorch Lightning`, `Training Framework`, `Distributed Training`, `DDP`, `FSDP`, `DeepSpeed`, `High-Level API`, `Callbacks`, `Best Practices`, `Scalable` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# PyTorch Lightning - High-Level Training Framework
|
||||
|
||||
## Quick start
|
||||
|
||||
PyTorch Lightning organizes PyTorch code to eliminate boilerplate while maintaining flexibility.
|
||||
|
||||
**Installation**:
|
||||
```bash
|
||||
pip install lightning
|
||||
```
|
||||
|
||||
**Convert PyTorch to Lightning** (3 steps):
|
||||
|
||||
```python
|
||||
import lightning as L
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.utils.data import DataLoader, Dataset
|
||||
|
||||
# Step 1: Define LightningModule (organize your PyTorch code)
|
||||
class LitModel(L.LightningModule):
|
||||
def __init__(self, hidden_size=128):
|
||||
super().__init__()
|
||||
self.model = nn.Sequential(
|
||||
nn.Linear(28 * 28, hidden_size),
|
||||
nn.ReLU(),
|
||||
nn.Linear(hidden_size, 10)
|
||||
)
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
y_hat = self.model(x)
|
||||
loss = nn.functional.cross_entropy(y_hat, y)
|
||||
self.log('train_loss', loss) # Auto-logged to TensorBoard
|
||||
return loss
|
||||
|
||||
def configure_optimizers(self):
|
||||
return torch.optim.Adam(self.parameters(), lr=1e-3)
|
||||
|
||||
# Step 2: Create data
|
||||
train_loader = DataLoader(train_dataset, batch_size=32)
|
||||
|
||||
# Step 3: Train with Trainer (handles everything else!)
|
||||
trainer = L.Trainer(max_epochs=10, accelerator='gpu', devices=2)
|
||||
model = LitModel()
|
||||
trainer.fit(model, train_loader)
|
||||
```
|
||||
|
||||
**That's it!** Trainer handles:
|
||||
- GPU/TPU/CPU switching
|
||||
- Distributed training (DDP, FSDP, DeepSpeed)
|
||||
- Mixed precision (FP16, BF16)
|
||||
- Gradient accumulation
|
||||
- Checkpointing
|
||||
- Logging
|
||||
- Progress bars
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: From PyTorch to Lightning
|
||||
|
||||
**Original PyTorch code**:
|
||||
```python
|
||||
model = MyModel()
|
||||
optimizer = torch.optim.Adam(model.parameters())
|
||||
model.to('cuda')
|
||||
|
||||
for epoch in range(max_epochs):
|
||||
for batch in train_loader:
|
||||
batch = batch.to('cuda')
|
||||
optimizer.zero_grad()
|
||||
loss = model(batch)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
```
|
||||
|
||||
**Lightning version**:
|
||||
```python
|
||||
class LitModel(L.LightningModule):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.model = MyModel()
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
loss = self.model(batch) # No .to('cuda') needed!
|
||||
return loss
|
||||
|
||||
def configure_optimizers(self):
|
||||
return torch.optim.Adam(self.parameters())
|
||||
|
||||
# Train
|
||||
trainer = L.Trainer(max_epochs=10, accelerator='gpu')
|
||||
trainer.fit(LitModel(), train_loader)
|
||||
```
|
||||
|
||||
**Benefits**: 40+ lines → 15 lines, no device management, automatic distributed
|
||||
|
||||
### Workflow 2: Validation and testing
|
||||
|
||||
```python
|
||||
class LitModel(L.LightningModule):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.model = MyModel()
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
y_hat = self.model(x)
|
||||
loss = nn.functional.cross_entropy(y_hat, y)
|
||||
self.log('train_loss', loss)
|
||||
return loss
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
y_hat = self.model(x)
|
||||
val_loss = nn.functional.cross_entropy(y_hat, y)
|
||||
acc = (y_hat.argmax(dim=1) == y).float().mean()
|
||||
self.log('val_loss', val_loss)
|
||||
self.log('val_acc', acc)
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
y_hat = self.model(x)
|
||||
test_loss = nn.functional.cross_entropy(y_hat, y)
|
||||
self.log('test_loss', test_loss)
|
||||
|
||||
def configure_optimizers(self):
|
||||
return torch.optim.Adam(self.parameters(), lr=1e-3)
|
||||
|
||||
# Train with validation
|
||||
trainer = L.Trainer(max_epochs=10)
|
||||
trainer.fit(model, train_loader, val_loader)
|
||||
|
||||
# Test
|
||||
trainer.test(model, test_loader)
|
||||
```
|
||||
|
||||
**Automatic features**:
|
||||
- Validation runs every epoch by default
|
||||
- Metrics logged to TensorBoard
|
||||
- Best model checkpointing based on val_loss
|
||||
|
||||
### Workflow 3: Distributed training (DDP)
|
||||
|
||||
```python
|
||||
# Same code as single GPU!
|
||||
model = LitModel()
|
||||
|
||||
# 8 GPUs with DDP (automatic!)
|
||||
trainer = L.Trainer(
|
||||
accelerator='gpu',
|
||||
devices=8,
|
||||
strategy='ddp' # Or 'fsdp', 'deepspeed'
|
||||
)
|
||||
|
||||
trainer.fit(model, train_loader)
|
||||
```
|
||||
|
||||
**Launch**:
|
||||
```bash
|
||||
# Single command, Lightning handles the rest
|
||||
python train.py
|
||||
```
|
||||
|
||||
**No changes needed**:
|
||||
- Automatic data distribution
|
||||
- Gradient synchronization
|
||||
- Multi-node support (just set `num_nodes=2`)
|
||||
|
||||
### Workflow 4: Callbacks for monitoring
|
||||
|
||||
```python
|
||||
from lightning.pytorch.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor
|
||||
|
||||
# Create callbacks
|
||||
checkpoint = ModelCheckpoint(
|
||||
monitor='val_loss',
|
||||
mode='min',
|
||||
save_top_k=3,
|
||||
filename='model-{epoch:02d}-{val_loss:.2f}'
|
||||
)
|
||||
|
||||
early_stop = EarlyStopping(
|
||||
monitor='val_loss',
|
||||
patience=5,
|
||||
mode='min'
|
||||
)
|
||||
|
||||
lr_monitor = LearningRateMonitor(logging_interval='epoch')
|
||||
|
||||
# Add to Trainer
|
||||
trainer = L.Trainer(
|
||||
max_epochs=100,
|
||||
callbacks=[checkpoint, early_stop, lr_monitor]
|
||||
)
|
||||
|
||||
trainer.fit(model, train_loader, val_loader)
|
||||
```
|
||||
|
||||
**Result**:
|
||||
- Auto-saves best 3 models
|
||||
- Stops early if no improvement for 5 epochs
|
||||
- Logs learning rate to TensorBoard
|
||||
|
||||
### Workflow 5: Learning rate scheduling
|
||||
|
||||
```python
|
||||
class LitModel(L.LightningModule):
|
||||
# ... (training_step, etc.)
|
||||
|
||||
def configure_optimizers(self):
|
||||
optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
|
||||
|
||||
# Cosine annealing
|
||||
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
|
||||
optimizer,
|
||||
T_max=100,
|
||||
eta_min=1e-5
|
||||
)
|
||||
|
||||
return {
|
||||
'optimizer': optimizer,
|
||||
'lr_scheduler': {
|
||||
'scheduler': scheduler,
|
||||
'interval': 'epoch', # Update per epoch
|
||||
'frequency': 1
|
||||
}
|
||||
}
|
||||
|
||||
# Learning rate auto-logged!
|
||||
trainer = L.Trainer(max_epochs=100)
|
||||
trainer.fit(model, train_loader)
|
||||
```
|
||||
|
||||
## When to use vs alternatives
|
||||
|
||||
**Use PyTorch Lightning when**:
|
||||
- Want clean, organized code
|
||||
- Need production-ready training loops
|
||||
- Switching between single GPU, multi-GPU, TPU
|
||||
- Want built-in callbacks and logging
|
||||
- Team collaboration (standardized structure)
|
||||
|
||||
**Key advantages**:
|
||||
- **Organized**: Separates research code from engineering
|
||||
- **Automatic**: DDP, FSDP, DeepSpeed with 1 line
|
||||
- **Callbacks**: Modular training extensions
|
||||
- **Reproducible**: Less boilerplate = fewer bugs
|
||||
- **Tested**: 1M+ downloads/month, battle-tested
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **Accelerate**: Minimal changes to existing code, more flexibility
|
||||
- **Ray Train**: Multi-node orchestration, hyperparameter tuning
|
||||
- **Raw PyTorch**: Maximum control, learning purposes
|
||||
- **Keras**: TensorFlow ecosystem
|
||||
|
||||
## Common issues
|
||||
|
||||
**Issue: Loss not decreasing**
|
||||
|
||||
Check data and model setup:
|
||||
```python
|
||||
# Add to training_step
|
||||
def training_step(self, batch, batch_idx):
|
||||
if batch_idx == 0:
|
||||
print(f"Batch shape: {batch[0].shape}")
|
||||
print(f"Labels: {batch[1]}")
|
||||
loss = ...
|
||||
return loss
|
||||
```
|
||||
|
||||
**Issue: Out of memory**
|
||||
|
||||
Reduce batch size or use gradient accumulation:
|
||||
```python
|
||||
trainer = L.Trainer(
|
||||
accumulate_grad_batches=4, # Effective batch = batch_size × 4
|
||||
precision='bf16' # Or 'fp16', reduces memory 50%
|
||||
)
|
||||
```
|
||||
|
||||
**Issue: Validation not running**
|
||||
|
||||
Ensure you pass val_loader:
|
||||
```python
|
||||
# WRONG
|
||||
trainer.fit(model, train_loader)
|
||||
|
||||
# CORRECT
|
||||
trainer.fit(model, train_loader, val_loader)
|
||||
```
|
||||
|
||||
**Issue: DDP spawns multiple processes unexpectedly**
|
||||
|
||||
Lightning auto-detects GPUs. Explicitly set devices:
|
||||
```python
|
||||
# Test on CPU first
|
||||
trainer = L.Trainer(accelerator='cpu', devices=1)
|
||||
|
||||
# Then GPU
|
||||
trainer = L.Trainer(accelerator='gpu', devices=1)
|
||||
```
|
||||
|
||||
## Advanced topics
|
||||
|
||||
**Callbacks**: See [references/callbacks.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\pytorch-lightning/references/callbacks.md) for EarlyStopping, ModelCheckpoint, custom callbacks, and callback hooks.
|
||||
|
||||
**Distributed strategies**: See [references/distributed.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\pytorch-lightning/references/distributed.md) for DDP, FSDP, DeepSpeed ZeRO integration, multi-node setup.
|
||||
|
||||
**Hyperparameter tuning**: See [references/hyperparameter-tuning.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\pytorch-lightning/references/hyperparameter-tuning.md) for integration with Optuna, Ray Tune, and WandB sweeps.
|
||||
|
||||
## Hardware requirements
|
||||
|
||||
- **CPU**: Works (good for debugging)
|
||||
- **Single GPU**: Works
|
||||
- **Multi-GPU**: DDP (default), FSDP, or DeepSpeed
|
||||
- **Multi-node**: DDP, FSDP, DeepSpeed
|
||||
- **TPU**: Supported (8 cores)
|
||||
- **Apple MPS**: Supported
|
||||
|
||||
**Precision options**:
|
||||
- FP32 (default)
|
||||
- FP16 (V100, older GPUs)
|
||||
- BF16 (A100/H100, recommended)
|
||||
- FP8 (H100)
|
||||
|
||||
## Resources
|
||||
|
||||
- Docs: https://lightning.ai/docs/pytorch/stable/
|
||||
- GitHub: https://github.com/Lightning-AI/pytorch-lightning ⭐ 29,000+
|
||||
- Version: 2.5.5+
|
||||
- Examples: https://github.com/Lightning-AI/pytorch-lightning/tree/master/examples
|
||||
- Discord: https://discord.gg/lightning-ai
|
||||
- Used by: Kaggle winners, research labs, production teams
|
||||
@@ -0,0 +1,522 @@
|
||||
---
|
||||
title: "Qdrant — Vector search engine for production RAG systems"
|
||||
sidebar_label: "Qdrant"
|
||||
description: "Vector search engine for production RAG systems"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Qdrant
|
||||
|
||||
Vector search engine for production RAG systems.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/qdrant` |
|
||||
| Path | `optional-skills/mlops\qdrant` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `qdrant-client>=1.14.0` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `RAG`, `Vector Search`, `Qdrant`, `Semantic Search`, `Embeddings`, `Similarity Search`, `HNSW`, `Production`, `Distributed` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Qdrant - Vector Similarity Search Engine
|
||||
|
||||
High-performance vector database written in Rust for production RAG and semantic search.
|
||||
|
||||
## When to use Qdrant
|
||||
|
||||
**Use Qdrant when:**
|
||||
- Building production RAG systems requiring low latency
|
||||
- Need hybrid search (vectors + metadata filtering)
|
||||
- Require horizontal scaling with sharding/replication
|
||||
- Want on-premise deployment with full data control
|
||||
- Need multi-vector storage per record (dense + sparse)
|
||||
- Building real-time recommendation systems
|
||||
|
||||
**Key features:**
|
||||
- **Rust-powered**: Memory-safe, high performance
|
||||
- **Rich filtering**: Filter by any payload field during search
|
||||
- **Multiple vectors**: Dense, sparse, multi-dense per point
|
||||
- **Quantization**: Scalar, product, binary for memory efficiency
|
||||
- **Distributed**: Raft consensus, sharding, replication
|
||||
- **REST + gRPC**: Both APIs with full feature parity
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **Chroma**: Simpler setup, embedded use cases
|
||||
- **FAISS**: Maximum raw speed, research/batch processing
|
||||
- **Pinecone**: Fully managed, zero ops preferred
|
||||
- **Weaviate**: GraphQL preference, built-in vectorizers
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Python client
|
||||
pip install qdrant-client
|
||||
|
||||
# Docker (recommended for development)
|
||||
docker run -p 6333:6333 -p 6334:6334 qdrant/qdrant
|
||||
|
||||
# Docker with persistent storage
|
||||
docker run -p 6333:6333 -p 6334:6334 \
|
||||
-v $(pwd)/qdrant_storage:/qdrant/storage \
|
||||
qdrant/qdrant
|
||||
```
|
||||
|
||||
### Basic usage
|
||||
|
||||
```python
|
||||
from qdrant_client import QdrantClient
|
||||
from qdrant_client.models import Distance, VectorParams, PointStruct
|
||||
|
||||
# Connect to Qdrant
|
||||
client = QdrantClient(host="localhost", port=6333)
|
||||
|
||||
# Create collection
|
||||
client.create_collection(
|
||||
collection_name="documents",
|
||||
vectors_config=VectorParams(size=384, distance=Distance.COSINE)
|
||||
)
|
||||
|
||||
# Insert vectors with payload
|
||||
client.upsert(
|
||||
collection_name="documents",
|
||||
points=[
|
||||
PointStruct(
|
||||
id=1,
|
||||
vector=[0.1, 0.2, ...], # 384-dim vector
|
||||
payload={"title": "Doc 1", "category": "tech"}
|
||||
),
|
||||
PointStruct(
|
||||
id=2,
|
||||
vector=[0.3, 0.4, ...],
|
||||
payload={"title": "Doc 2", "category": "science"}
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
# Search with filtering (query_points is the current API; client.search is removed in qdrant-client 1.14+)
|
||||
response = client.query_points(
|
||||
collection_name="documents",
|
||||
query=[0.15, 0.25, ...],
|
||||
query_filter={
|
||||
"must": [{"key": "category", "match": {"value": "tech"}}]
|
||||
},
|
||||
limit=10
|
||||
)
|
||||
|
||||
for point in response.points:
|
||||
print(f"ID: {point.id}, Score: {point.score}, Payload: {point.payload}")
|
||||
```
|
||||
|
||||
## Core concepts
|
||||
|
||||
### Points - Basic data unit
|
||||
|
||||
```python
|
||||
from qdrant_client.models import PointStruct
|
||||
|
||||
# Point = ID + Vector(s) + Payload
|
||||
point = PointStruct(
|
||||
id=123, # Integer or UUID string
|
||||
vector=[0.1, 0.2, 0.3, ...], # Dense vector
|
||||
payload={ # Arbitrary JSON metadata
|
||||
"title": "Document title",
|
||||
"category": "tech",
|
||||
"timestamp": 1699900000,
|
||||
"tags": ["python", "ml"]
|
||||
}
|
||||
)
|
||||
|
||||
# Batch upsert (recommended)
|
||||
client.upsert(
|
||||
collection_name="documents",
|
||||
points=[point1, point2, point3],
|
||||
wait=True # Wait for indexing
|
||||
)
|
||||
```
|
||||
|
||||
### Collections - Vector containers
|
||||
|
||||
```python
|
||||
from qdrant_client.models import VectorParams, Distance, HnswConfigDiff
|
||||
|
||||
# Create with HNSW configuration
|
||||
client.create_collection(
|
||||
collection_name="documents",
|
||||
vectors_config=VectorParams(
|
||||
size=384, # Vector dimensions
|
||||
distance=Distance.COSINE # COSINE, EUCLID, DOT, MANHATTAN
|
||||
),
|
||||
hnsw_config=HnswConfigDiff(
|
||||
m=16, # Connections per node (default 16)
|
||||
ef_construct=100, # Build-time accuracy (default 100)
|
||||
full_scan_threshold=10000 # Switch to brute force below this
|
||||
),
|
||||
on_disk_payload=True # Store payload on disk
|
||||
)
|
||||
|
||||
# Collection info
|
||||
info = client.get_collection("documents")
|
||||
print(f"Points: {info.points_count}, Vectors: {info.vectors_count}")
|
||||
```
|
||||
|
||||
### Distance metrics
|
||||
|
||||
| Metric | Use Case | Range |
|
||||
|--------|----------|-------|
|
||||
| `COSINE` | Text embeddings, normalized vectors | 0 to 2 |
|
||||
| `EUCLID` | Spatial data, image features | 0 to ∞ |
|
||||
| `DOT` | Recommendations, unnormalized | -∞ to ∞ |
|
||||
| `MANHATTAN` | Sparse features, discrete data | 0 to ∞ |
|
||||
|
||||
## Search operations
|
||||
|
||||
### Basic search
|
||||
|
||||
```python
|
||||
# Simple nearest neighbor search (returns a QueryResponse; use .points)
|
||||
response = client.query_points(
|
||||
collection_name="documents",
|
||||
query=[0.1, 0.2, ...],
|
||||
limit=10,
|
||||
with_payload=True,
|
||||
with_vectors=False # Don't return vectors (faster)
|
||||
)
|
||||
results = response.points
|
||||
```
|
||||
|
||||
### Filtered search
|
||||
|
||||
```python
|
||||
from qdrant_client.models import Filter, FieldCondition, MatchValue, Range
|
||||
|
||||
# Complex filtering
|
||||
response = client.query_points(
|
||||
collection_name="documents",
|
||||
query=query_embedding,
|
||||
query_filter=Filter(
|
||||
must=[
|
||||
FieldCondition(key="category", match=MatchValue(value="tech")),
|
||||
FieldCondition(key="timestamp", range=Range(gte=1699000000))
|
||||
],
|
||||
must_not=[
|
||||
FieldCondition(key="status", match=MatchValue(value="archived"))
|
||||
]
|
||||
),
|
||||
limit=10
|
||||
).points
|
||||
|
||||
# Shorthand filter syntax
|
||||
response = client.query_points(
|
||||
collection_name="documents",
|
||||
query=query_embedding,
|
||||
query_filter={
|
||||
"must": [
|
||||
{"key": "category", "match": {"value": "tech"}},
|
||||
{"key": "price", "range": {"gte": 10, "lte": 100}}
|
||||
]
|
||||
},
|
||||
limit=10
|
||||
).points
|
||||
```
|
||||
|
||||
### Batch search
|
||||
|
||||
```python
|
||||
from qdrant_client.models import QueryRequest
|
||||
|
||||
# Multiple queries in one request (search_batch is replaced by query_batch_points)
|
||||
responses = client.query_batch_points(
|
||||
collection_name="documents",
|
||||
requests=[
|
||||
QueryRequest(query=[0.1, ...], limit=5),
|
||||
QueryRequest(query=[0.2, ...], limit=5, filter={"must": [...]}),
|
||||
QueryRequest(query=[0.3, ...], limit=10)
|
||||
]
|
||||
)
|
||||
# Each element is a QueryResponse; use .points
|
||||
for resp in responses:
|
||||
for point in resp.points:
|
||||
print(point.id, point.score)
|
||||
```
|
||||
|
||||
## RAG integration
|
||||
|
||||
### With sentence-transformers
|
||||
|
||||
```python
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from qdrant_client import QdrantClient
|
||||
from qdrant_client.models import VectorParams, Distance, PointStruct
|
||||
|
||||
# Initialize
|
||||
encoder = SentenceTransformer("all-MiniLM-L6-v2")
|
||||
client = QdrantClient(host="localhost", port=6333)
|
||||
|
||||
# Create collection
|
||||
client.create_collection(
|
||||
collection_name="knowledge_base",
|
||||
vectors_config=VectorParams(size=384, distance=Distance.COSINE)
|
||||
)
|
||||
|
||||
# Index documents
|
||||
documents = [
|
||||
{"id": 1, "text": "Python is a programming language", "source": "wiki"},
|
||||
{"id": 2, "text": "Machine learning uses algorithms", "source": "textbook"},
|
||||
]
|
||||
|
||||
points = [
|
||||
PointStruct(
|
||||
id=doc["id"],
|
||||
vector=encoder.encode(doc["text"]).tolist(),
|
||||
payload={"text": doc["text"], "source": doc["source"]}
|
||||
)
|
||||
for doc in documents
|
||||
]
|
||||
client.upsert(collection_name="knowledge_base", points=points)
|
||||
|
||||
# RAG retrieval
|
||||
def retrieve(query: str, top_k: int = 5) -> list[dict]:
|
||||
query_vector = encoder.encode(query).tolist()
|
||||
response = client.query_points(
|
||||
collection_name="knowledge_base",
|
||||
query=query_vector,
|
||||
limit=top_k
|
||||
)
|
||||
return [{"text": r.payload["text"], "score": r.score} for r in response.points]
|
||||
|
||||
# Use in RAG pipeline
|
||||
context = retrieve("What is Python?")
|
||||
prompt = f"Context: {context}\n\nQuestion: What is Python?"
|
||||
```
|
||||
|
||||
### With LangChain
|
||||
|
||||
```python
|
||||
from langchain_community.vectorstores import Qdrant
|
||||
from langchain_community.embeddings import HuggingFaceEmbeddings
|
||||
|
||||
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
||||
vectorstore = Qdrant.from_documents(documents, embeddings, url="http://localhost:6333", collection_name="docs")
|
||||
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
|
||||
```
|
||||
|
||||
### With LlamaIndex
|
||||
|
||||
```python
|
||||
from llama_index.vector_stores.qdrant import QdrantVectorStore
|
||||
from llama_index.core import VectorStoreIndex, StorageContext
|
||||
|
||||
vector_store = QdrantVectorStore(client=client, collection_name="llama_docs")
|
||||
storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
||||
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
|
||||
query_engine = index.as_query_engine()
|
||||
```
|
||||
|
||||
## Multi-vector support
|
||||
|
||||
### Named vectors (different embedding models)
|
||||
|
||||
```python
|
||||
from qdrant_client.models import VectorParams, Distance
|
||||
|
||||
# Collection with multiple vector types
|
||||
client.create_collection(
|
||||
collection_name="hybrid_search",
|
||||
vectors_config={
|
||||
"dense": VectorParams(size=384, distance=Distance.COSINE),
|
||||
"sparse": VectorParams(size=30000, distance=Distance.DOT)
|
||||
}
|
||||
)
|
||||
|
||||
# Insert with named vectors
|
||||
client.upsert(
|
||||
collection_name="hybrid_search",
|
||||
points=[
|
||||
PointStruct(
|
||||
id=1,
|
||||
vector={
|
||||
"dense": dense_embedding,
|
||||
"sparse": sparse_embedding
|
||||
},
|
||||
payload={"text": "document text"}
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
# Search specific named vector (pass the vector name via `using`)
|
||||
response = client.query_points(
|
||||
collection_name="hybrid_search",
|
||||
query=query_dense,
|
||||
using="dense", # Specify which named vector to search
|
||||
limit=10
|
||||
)
|
||||
results = response.points
|
||||
```
|
||||
|
||||
### Sparse vectors (BM25, SPLADE)
|
||||
|
||||
```python
|
||||
from qdrant_client.models import SparseVectorParams, SparseIndexParams, SparseVector
|
||||
|
||||
# Collection with sparse vectors
|
||||
client.create_collection(
|
||||
collection_name="sparse_search",
|
||||
vectors_config={},
|
||||
sparse_vectors_config={"text": SparseVectorParams(index=SparseIndexParams(on_disk=False))}
|
||||
)
|
||||
|
||||
# Insert sparse vector
|
||||
client.upsert(
|
||||
collection_name="sparse_search",
|
||||
points=[PointStruct(id=1, vector={"text": SparseVector(indices=[1, 5, 100], values=[0.5, 0.8, 0.2])}, payload={"text": "document"})]
|
||||
)
|
||||
```
|
||||
|
||||
## Quantization (memory optimization)
|
||||
|
||||
```python
|
||||
from qdrant_client.models import ScalarQuantization, ScalarQuantizationConfig, ScalarType
|
||||
|
||||
# Scalar quantization (4x memory reduction)
|
||||
client.create_collection(
|
||||
collection_name="quantized",
|
||||
vectors_config=VectorParams(size=384, distance=Distance.COSINE),
|
||||
quantization_config=ScalarQuantization(
|
||||
scalar=ScalarQuantizationConfig(
|
||||
type=ScalarType.INT8,
|
||||
quantile=0.99, # Clip outliers
|
||||
always_ram=True # Keep quantized in RAM
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# Search with rescoring
|
||||
response = client.query_points(
|
||||
collection_name="quantized",
|
||||
query=query,
|
||||
search_params={"quantization": {"rescore": True}}, # Rescore top results
|
||||
limit=10
|
||||
)
|
||||
results = response.points
|
||||
```
|
||||
|
||||
## Payload indexing
|
||||
|
||||
```python
|
||||
from qdrant_client.models import PayloadSchemaType
|
||||
|
||||
# Create payload index for faster filtering
|
||||
client.create_payload_index(
|
||||
collection_name="documents",
|
||||
field_name="category",
|
||||
field_schema=PayloadSchemaType.KEYWORD
|
||||
)
|
||||
|
||||
client.create_payload_index(
|
||||
collection_name="documents",
|
||||
field_name="timestamp",
|
||||
field_schema=PayloadSchemaType.INTEGER
|
||||
)
|
||||
|
||||
# Index types: KEYWORD, INTEGER, FLOAT, GEO, TEXT (full-text), BOOL
|
||||
```
|
||||
|
||||
## Production deployment
|
||||
|
||||
### Qdrant Cloud
|
||||
|
||||
```python
|
||||
from qdrant_client import QdrantClient
|
||||
|
||||
# Connect to Qdrant Cloud
|
||||
client = QdrantClient(
|
||||
url="https://your-cluster.cloud.qdrant.io",
|
||||
api_key="your-api-key"
|
||||
)
|
||||
```
|
||||
|
||||
### Performance tuning
|
||||
|
||||
```python
|
||||
# Optimize for search speed (higher recall)
|
||||
client.update_collection(
|
||||
collection_name="documents",
|
||||
hnsw_config=HnswConfigDiff(ef_construct=200, m=32)
|
||||
)
|
||||
|
||||
# Optimize for indexing speed (bulk loads)
|
||||
client.update_collection(
|
||||
collection_name="documents",
|
||||
optimizer_config={"indexing_threshold": 20000}
|
||||
)
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
1. **Batch operations** - Use batch upsert/search for efficiency
|
||||
2. **Payload indexing** - Index fields used in filters
|
||||
3. **Quantization** - Enable for large collections (>1M vectors)
|
||||
4. **Sharding** - Use for collections >10M vectors
|
||||
5. **On-disk storage** - Enable `on_disk_payload` for large payloads
|
||||
6. **Connection pooling** - Reuse client instances
|
||||
|
||||
## Common issues
|
||||
|
||||
**Slow search with filters:**
|
||||
```python
|
||||
# Create payload index for filtered fields
|
||||
client.create_payload_index(
|
||||
collection_name="docs",
|
||||
field_name="category",
|
||||
field_schema=PayloadSchemaType.KEYWORD
|
||||
)
|
||||
```
|
||||
|
||||
**Out of memory:**
|
||||
```python
|
||||
# Enable quantization and on-disk storage
|
||||
client.create_collection(
|
||||
collection_name="large_collection",
|
||||
vectors_config=VectorParams(size=384, distance=Distance.COSINE),
|
||||
quantization_config=ScalarQuantization(...),
|
||||
on_disk_payload=True
|
||||
)
|
||||
```
|
||||
|
||||
**Connection issues:**
|
||||
```python
|
||||
# Use timeout and retry
|
||||
client = QdrantClient(
|
||||
host="localhost",
|
||||
port=6333,
|
||||
timeout=30,
|
||||
prefer_grpc=True # gRPC for better performance
|
||||
)
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- **[Advanced Usage](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\qdrant/references/advanced-usage.md)** - Distributed mode, hybrid search, recommendations
|
||||
- **[Troubleshooting](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\qdrant/references/troubleshooting.md)** - Common issues, debugging, performance tuning
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/qdrant/qdrant (22k+ stars)
|
||||
- **Docs**: https://qdrant.tech/documentation/
|
||||
- **Python Client**: https://github.com/qdrant/qdrant-client
|
||||
- **Cloud**: https://cloud.qdrant.io
|
||||
- **Version**: 1.14.0+
|
||||
- **License**: Apache 2.0
|
||||
@@ -0,0 +1,609 @@
|
||||
---
|
||||
title: "Dspy — DSPy: declarative LM programs, auto-optimize prompts, RAG"
|
||||
sidebar_label: "Dspy"
|
||||
description: "DSPy: declarative LM programs, auto-optimize prompts, RAG"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Dspy
|
||||
|
||||
DSPy: declarative LM programs, auto-optimize prompts, RAG.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/dspy` |
|
||||
| Path | `optional-skills/mlops\research\dspy` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `dspy`, `openai`, `anthropic` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Prompt Engineering`, `DSPy`, `Declarative Programming`, `RAG`, `Agents`, `Prompt Optimization`, `LM Programming`, `Stanford NLP`, `Automatic Optimization`, `Modular AI` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# DSPy: Declarative Language Model Programming
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use DSPy when you need to:
|
||||
- **Build complex AI systems** with multiple components and workflows
|
||||
- **Program LMs declaratively** instead of manual prompt engineering
|
||||
- **Optimize prompts automatically** using data-driven methods
|
||||
- **Create modular AI pipelines** that are maintainable and portable
|
||||
- **Improve model outputs systematically** with optimizers
|
||||
- **Build RAG systems, agents, or classifiers** with better reliability
|
||||
|
||||
**GitHub Stars**: 22,000+ | **Created By**: Stanford NLP
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Stable release
|
||||
pip install dspy
|
||||
|
||||
# Latest development version
|
||||
pip install git+https://github.com/stanfordnlp/dspy.git
|
||||
|
||||
# With specific LM providers
|
||||
pip install dspy[openai] # OpenAI
|
||||
pip install dspy[anthropic] # Anthropic Claude
|
||||
pip install dspy[all] # All providers
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Basic Example: Question Answering
|
||||
|
||||
```python
|
||||
import dspy
|
||||
|
||||
# Configure your language model
|
||||
lm = dspy.Claude(model="claude-sonnet-4-5-20250929")
|
||||
dspy.settings.configure(lm=lm)
|
||||
|
||||
# Define a signature (input → output)
|
||||
class QA(dspy.Signature):
|
||||
"""Answer questions with short factual answers."""
|
||||
question = dspy.InputField()
|
||||
answer = dspy.OutputField(desc="often between 1 and 5 words")
|
||||
|
||||
# Create a module
|
||||
qa = dspy.Predict(QA)
|
||||
|
||||
# Use it
|
||||
response = qa(question="What is the capital of France?")
|
||||
print(response.answer) # "Paris"
|
||||
```
|
||||
|
||||
### Chain of Thought Reasoning
|
||||
|
||||
```python
|
||||
import dspy
|
||||
|
||||
lm = dspy.Claude(model="claude-sonnet-4-5-20250929")
|
||||
dspy.settings.configure(lm=lm)
|
||||
|
||||
# Use ChainOfThought for better reasoning
|
||||
class MathProblem(dspy.Signature):
|
||||
"""Solve math word problems."""
|
||||
problem = dspy.InputField()
|
||||
answer = dspy.OutputField(desc="numerical answer")
|
||||
|
||||
# ChainOfThought generates reasoning steps automatically
|
||||
cot = dspy.ChainOfThought(MathProblem)
|
||||
|
||||
response = cot(problem="If John has 5 apples and gives 2 to Mary, how many does he have?")
|
||||
print(response.rationale) # Shows reasoning steps
|
||||
print(response.answer) # "3"
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### 1. Signatures
|
||||
|
||||
Signatures define the structure of your AI task (inputs → outputs):
|
||||
|
||||
```python
|
||||
# Inline signature (simple)
|
||||
qa = dspy.Predict("question -> answer")
|
||||
|
||||
# Class signature (detailed)
|
||||
class Summarize(dspy.Signature):
|
||||
"""Summarize text into key points."""
|
||||
text = dspy.InputField()
|
||||
summary = dspy.OutputField(desc="bullet points, 3-5 items")
|
||||
|
||||
summarizer = dspy.ChainOfThought(Summarize)
|
||||
```
|
||||
|
||||
**When to use each:**
|
||||
- **Inline**: Quick prototyping, simple tasks
|
||||
- **Class**: Complex tasks, type hints, better documentation
|
||||
|
||||
### 2. Modules
|
||||
|
||||
Modules are reusable components that transform inputs to outputs:
|
||||
|
||||
#### dspy.Predict
|
||||
Basic prediction module:
|
||||
|
||||
```python
|
||||
predictor = dspy.Predict("context, question -> answer")
|
||||
result = predictor(context="Paris is the capital of France",
|
||||
question="What is the capital?")
|
||||
```
|
||||
|
||||
#### dspy.ChainOfThought
|
||||
Generates reasoning steps before answering:
|
||||
|
||||
```python
|
||||
cot = dspy.ChainOfThought("question -> answer")
|
||||
result = cot(question="Why is the sky blue?")
|
||||
print(result.rationale) # Reasoning steps
|
||||
print(result.answer) # Final answer
|
||||
```
|
||||
|
||||
#### dspy.ReAct
|
||||
Agent-like reasoning with tools:
|
||||
|
||||
```python
|
||||
from dspy.predict import ReAct
|
||||
|
||||
class SearchQA(dspy.Signature):
|
||||
"""Answer questions using search."""
|
||||
question = dspy.InputField()
|
||||
answer = dspy.OutputField()
|
||||
|
||||
def search_tool(query: str) -> str:
|
||||
"""Search Wikipedia."""
|
||||
# Your search implementation
|
||||
return results
|
||||
|
||||
react = ReAct(SearchQA, tools=[search_tool])
|
||||
result = react(question="When was Python created?")
|
||||
```
|
||||
|
||||
#### dspy.ProgramOfThought
|
||||
Generates and executes code for reasoning:
|
||||
|
||||
```python
|
||||
pot = dspy.ProgramOfThought("question -> answer")
|
||||
result = pot(question="What is 15% of 240?")
|
||||
# Generates: answer = 240 * 0.15
|
||||
```
|
||||
|
||||
### 3. Optimizers
|
||||
|
||||
Optimizers improve your modules automatically using training data:
|
||||
|
||||
#### BootstrapFewShot
|
||||
Learns from examples:
|
||||
|
||||
```python
|
||||
from dspy.teleprompt import BootstrapFewShot
|
||||
|
||||
# Training data
|
||||
trainset = [
|
||||
dspy.Example(question="What is 2+2?", answer="4").with_inputs("question"),
|
||||
dspy.Example(question="What is 3+5?", answer="8").with_inputs("question"),
|
||||
]
|
||||
|
||||
# Define metric
|
||||
def validate_answer(example, pred, trace=None):
|
||||
return example.answer == pred.answer
|
||||
|
||||
# Optimize
|
||||
optimizer = BootstrapFewShot(metric=validate_answer, max_bootstrapped_demos=3)
|
||||
optimized_qa = optimizer.compile(qa, trainset=trainset)
|
||||
|
||||
# Now optimized_qa performs better!
|
||||
```
|
||||
|
||||
#### MIPRO (Most Important Prompt Optimization)
|
||||
Iteratively improves prompts:
|
||||
|
||||
```python
|
||||
from dspy.teleprompt import MIPRO
|
||||
|
||||
optimizer = MIPRO(
|
||||
metric=validate_answer,
|
||||
num_candidates=10,
|
||||
init_temperature=1.0
|
||||
)
|
||||
|
||||
optimized_cot = optimizer.compile(
|
||||
cot,
|
||||
trainset=trainset,
|
||||
num_trials=100
|
||||
)
|
||||
```
|
||||
|
||||
#### BootstrapFinetune
|
||||
Creates datasets for model fine-tuning:
|
||||
|
||||
```python
|
||||
from dspy.teleprompt import BootstrapFinetune
|
||||
|
||||
optimizer = BootstrapFinetune(metric=validate_answer)
|
||||
optimized_module = optimizer.compile(qa, trainset=trainset)
|
||||
|
||||
# Exports training data for fine-tuning
|
||||
```
|
||||
|
||||
### 4. Building Complex Systems
|
||||
|
||||
#### Multi-Stage Pipeline
|
||||
|
||||
```python
|
||||
import dspy
|
||||
|
||||
class MultiHopQA(dspy.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.retrieve = dspy.Retrieve(k=3)
|
||||
self.generate_query = dspy.ChainOfThought("question -> search_query")
|
||||
self.generate_answer = dspy.ChainOfThought("context, question -> answer")
|
||||
|
||||
def forward(self, question):
|
||||
# Stage 1: Generate search query
|
||||
search_query = self.generate_query(question=question).search_query
|
||||
|
||||
# Stage 2: Retrieve context
|
||||
passages = self.retrieve(search_query).passages
|
||||
context = "\n".join(passages)
|
||||
|
||||
# Stage 3: Generate answer
|
||||
answer = self.generate_answer(context=context, question=question).answer
|
||||
return dspy.Prediction(answer=answer, context=context)
|
||||
|
||||
# Use the pipeline
|
||||
qa_system = MultiHopQA()
|
||||
result = qa_system(question="Who wrote the book that inspired the movie Blade Runner?")
|
||||
```
|
||||
|
||||
#### RAG System with Optimization
|
||||
|
||||
```python
|
||||
import dspy
|
||||
from dspy.retrieve.chromadb_rm import ChromadbRM
|
||||
|
||||
# Configure retriever
|
||||
retriever = ChromadbRM(
|
||||
collection_name="documents",
|
||||
persist_directory="./chroma_db"
|
||||
)
|
||||
|
||||
class RAG(dspy.Module):
|
||||
def __init__(self, num_passages=3):
|
||||
super().__init__()
|
||||
self.retrieve = dspy.Retrieve(k=num_passages)
|
||||
self.generate = dspy.ChainOfThought("context, question -> answer")
|
||||
|
||||
def forward(self, question):
|
||||
context = self.retrieve(question).passages
|
||||
return self.generate(context=context, question=question)
|
||||
|
||||
# Create and optimize
|
||||
rag = RAG()
|
||||
|
||||
# Optimize with training data
|
||||
from dspy.teleprompt import BootstrapFewShot
|
||||
|
||||
optimizer = BootstrapFewShot(metric=validate_answer)
|
||||
optimized_rag = optimizer.compile(rag, trainset=trainset)
|
||||
```
|
||||
|
||||
## LM Provider Configuration
|
||||
|
||||
### Anthropic Claude
|
||||
|
||||
```python
|
||||
import dspy
|
||||
|
||||
lm = dspy.Claude(
|
||||
model="claude-sonnet-4-5-20250929",
|
||||
api_key="your-api-key", # Or set ANTHROPIC_API_KEY env var
|
||||
max_tokens=1000,
|
||||
temperature=0.7
|
||||
)
|
||||
dspy.settings.configure(lm=lm)
|
||||
```
|
||||
|
||||
### OpenAI
|
||||
|
||||
```python
|
||||
lm = dspy.OpenAI(
|
||||
model="gpt-4",
|
||||
api_key="your-api-key",
|
||||
max_tokens=1000
|
||||
)
|
||||
dspy.settings.configure(lm=lm)
|
||||
```
|
||||
|
||||
### Local Models (Ollama)
|
||||
|
||||
```python
|
||||
lm = dspy.OllamaLocal(
|
||||
model="llama3.1",
|
||||
base_url="http://localhost:11434"
|
||||
)
|
||||
dspy.settings.configure(lm=lm)
|
||||
```
|
||||
|
||||
### Multiple Models
|
||||
|
||||
```python
|
||||
# Different models for different tasks
|
||||
cheap_lm = dspy.OpenAI(model="gpt-3.5-turbo")
|
||||
strong_lm = dspy.Claude(model="claude-sonnet-4-5-20250929")
|
||||
|
||||
# Use cheap model for retrieval, strong model for reasoning
|
||||
with dspy.settings.context(lm=cheap_lm):
|
||||
context = retriever(question)
|
||||
|
||||
with dspy.settings.context(lm=strong_lm):
|
||||
answer = generator(context=context, question=question)
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Pattern 1: Structured Output
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class PersonInfo(BaseModel):
|
||||
name: str = Field(description="Full name")
|
||||
age: int = Field(description="Age in years")
|
||||
occupation: str = Field(description="Current job")
|
||||
|
||||
class ExtractPerson(dspy.Signature):
|
||||
"""Extract person information from text."""
|
||||
text = dspy.InputField()
|
||||
person: PersonInfo = dspy.OutputField()
|
||||
|
||||
extractor = dspy.TypedPredictor(ExtractPerson)
|
||||
result = extractor(text="John Doe is a 35-year-old software engineer.")
|
||||
print(result.person.name) # "John Doe"
|
||||
print(result.person.age) # 35
|
||||
```
|
||||
|
||||
### Pattern 2: Assertion-Driven Optimization
|
||||
|
||||
```python
|
||||
import dspy
|
||||
from dspy.primitives.assertions import assert_transform_module, backtrack_handler
|
||||
|
||||
class MathQA(dspy.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.solve = dspy.ChainOfThought("problem -> solution: float")
|
||||
|
||||
def forward(self, problem):
|
||||
solution = self.solve(problem=problem).solution
|
||||
|
||||
# Assert solution is numeric
|
||||
dspy.Assert(
|
||||
isinstance(float(solution), float),
|
||||
"Solution must be a number",
|
||||
backtrack=backtrack_handler
|
||||
)
|
||||
|
||||
return dspy.Prediction(solution=solution)
|
||||
```
|
||||
|
||||
### Pattern 3: Self-Consistency
|
||||
|
||||
```python
|
||||
import dspy
|
||||
from collections import Counter
|
||||
|
||||
class ConsistentQA(dspy.Module):
|
||||
def __init__(self, num_samples=5):
|
||||
super().__init__()
|
||||
self.qa = dspy.ChainOfThought("question -> answer")
|
||||
self.num_samples = num_samples
|
||||
|
||||
def forward(self, question):
|
||||
# Generate multiple answers
|
||||
answers = []
|
||||
for _ in range(self.num_samples):
|
||||
result = self.qa(question=question)
|
||||
answers.append(result.answer)
|
||||
|
||||
# Return most common answer
|
||||
most_common = Counter(answers).most_common(1)[0][0]
|
||||
return dspy.Prediction(answer=most_common)
|
||||
```
|
||||
|
||||
### Pattern 4: Retrieval with Reranking
|
||||
|
||||
```python
|
||||
class RerankedRAG(dspy.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.retrieve = dspy.Retrieve(k=10)
|
||||
self.rerank = dspy.Predict("question, passage -> relevance_score: float")
|
||||
self.answer = dspy.ChainOfThought("context, question -> answer")
|
||||
|
||||
def forward(self, question):
|
||||
# Retrieve candidates
|
||||
passages = self.retrieve(question).passages
|
||||
|
||||
# Rerank passages
|
||||
scored = []
|
||||
for passage in passages:
|
||||
score = float(self.rerank(question=question, passage=passage).relevance_score)
|
||||
scored.append((score, passage))
|
||||
|
||||
# Take top 3
|
||||
top_passages = [p for _, p in sorted(scored, reverse=True)[:3]]
|
||||
context = "\n\n".join(top_passages)
|
||||
|
||||
# Generate answer
|
||||
return self.answer(context=context, question=question)
|
||||
```
|
||||
|
||||
## Evaluation and Metrics
|
||||
|
||||
### Custom Metrics
|
||||
|
||||
```python
|
||||
def exact_match(example, pred, trace=None):
|
||||
"""Exact match metric."""
|
||||
return example.answer.lower() == pred.answer.lower()
|
||||
|
||||
def f1_score(example, pred, trace=None):
|
||||
"""F1 score for text overlap."""
|
||||
pred_tokens = set(pred.answer.lower().split())
|
||||
gold_tokens = set(example.answer.lower().split())
|
||||
|
||||
if not pred_tokens:
|
||||
return 0.0
|
||||
|
||||
precision = len(pred_tokens & gold_tokens) / len(pred_tokens)
|
||||
recall = len(pred_tokens & gold_tokens) / len(gold_tokens)
|
||||
|
||||
if precision + recall == 0:
|
||||
return 0.0
|
||||
|
||||
return 2 * (precision * recall) / (precision + recall)
|
||||
```
|
||||
|
||||
### Evaluation
|
||||
|
||||
```python
|
||||
from dspy.evaluate import Evaluate
|
||||
|
||||
# Create evaluator
|
||||
evaluator = Evaluate(
|
||||
devset=testset,
|
||||
metric=exact_match,
|
||||
num_threads=4,
|
||||
display_progress=True
|
||||
)
|
||||
|
||||
# Evaluate model
|
||||
score = evaluator(qa_system)
|
||||
print(f"Accuracy: {score}")
|
||||
|
||||
# Compare optimized vs unoptimized
|
||||
score_before = evaluator(qa)
|
||||
score_after = evaluator(optimized_qa)
|
||||
print(f"Improvement: {score_after - score_before:.2%}")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Start Simple, Iterate
|
||||
|
||||
```python
|
||||
# Start with Predict
|
||||
qa = dspy.Predict("question -> answer")
|
||||
|
||||
# Add reasoning if needed
|
||||
qa = dspy.ChainOfThought("question -> answer")
|
||||
|
||||
# Add optimization when you have data
|
||||
optimized_qa = optimizer.compile(qa, trainset=data)
|
||||
```
|
||||
|
||||
### 2. Use Descriptive Signatures
|
||||
|
||||
```python
|
||||
# ❌ Bad: Vague
|
||||
class Task(dspy.Signature):
|
||||
input = dspy.InputField()
|
||||
output = dspy.OutputField()
|
||||
|
||||
# ✅ Good: Descriptive
|
||||
class SummarizeArticle(dspy.Signature):
|
||||
"""Summarize news articles into 3-5 key points."""
|
||||
article = dspy.InputField(desc="full article text")
|
||||
summary = dspy.OutputField(desc="bullet points, 3-5 items")
|
||||
```
|
||||
|
||||
### 3. Optimize with Representative Data
|
||||
|
||||
```python
|
||||
# Create diverse training examples
|
||||
trainset = [
|
||||
dspy.Example(question="factual", answer="...).with_inputs("question"),
|
||||
dspy.Example(question="reasoning", answer="...").with_inputs("question"),
|
||||
dspy.Example(question="calculation", answer="...").with_inputs("question"),
|
||||
]
|
||||
|
||||
# Use validation set for metric
|
||||
def metric(example, pred, trace=None):
|
||||
return example.answer in pred.answer
|
||||
```
|
||||
|
||||
### 4. Save and Load Optimized Models
|
||||
|
||||
```python
|
||||
# Save
|
||||
optimized_qa.save("models/qa_v1.json")
|
||||
|
||||
# Load
|
||||
loaded_qa = dspy.ChainOfThought("question -> answer")
|
||||
loaded_qa.load("models/qa_v1.json")
|
||||
```
|
||||
|
||||
### 5. Monitor and Debug
|
||||
|
||||
```python
|
||||
# Enable tracing
|
||||
dspy.settings.configure(lm=lm, trace=[])
|
||||
|
||||
# Run prediction
|
||||
result = qa(question="...")
|
||||
|
||||
# Inspect trace
|
||||
for call in dspy.settings.trace:
|
||||
print(f"Prompt: {call['prompt']}")
|
||||
print(f"Response: {call['response']}")
|
||||
```
|
||||
|
||||
## Comparison to Other Approaches
|
||||
|
||||
| Feature | Manual Prompting | LangChain | DSPy |
|
||||
|---------|-----------------|-----------|------|
|
||||
| Prompt Engineering | Manual | Manual | Automatic |
|
||||
| Optimization | Trial & error | None | Data-driven |
|
||||
| Modularity | Low | Medium | High |
|
||||
| Type Safety | No | Limited | Yes (Signatures) |
|
||||
| Portability | Low | Medium | High |
|
||||
| Learning Curve | Low | Medium | Medium-High |
|
||||
|
||||
**When to choose DSPy:**
|
||||
- You have training data or can generate it
|
||||
- You need systematic prompt improvement
|
||||
- You're building complex multi-stage systems
|
||||
- You want to optimize across different LMs
|
||||
|
||||
**When to choose alternatives:**
|
||||
- Quick prototypes (manual prompting)
|
||||
- Simple chains with existing tools (LangChain)
|
||||
- Custom optimization logic needed
|
||||
|
||||
## Resources
|
||||
|
||||
- **Documentation**: https://dspy.ai
|
||||
- **GitHub**: https://github.com/stanfordnlp/dspy (22k+ stars)
|
||||
- **Discord**: https://discord.gg/XCGy2WDCQB
|
||||
- **Twitter**: @DSPyOSS
|
||||
- **Paper**: "DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines"
|
||||
|
||||
## See Also
|
||||
|
||||
- `references/modules.md` - Detailed module guide (Predict, ChainOfThought, ReAct, ProgramOfThought)
|
||||
- `references/optimizers.md` - Optimization algorithms (BootstrapFewShot, MIPRO, BootstrapFinetune)
|
||||
- `references/examples.md` - Real-world examples (RAG, agents, classifiers)
|
||||
@@ -0,0 +1,439 @@
|
||||
---
|
||||
title: "Saelens — Train sparse autoencoders to interpret model features"
|
||||
sidebar_label: "Saelens"
|
||||
description: "Train sparse autoencoders to interpret model features"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Saelens
|
||||
|
||||
Train sparse autoencoders to interpret model features.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/saelens` |
|
||||
| Path | `optional-skills/mlops\saelens` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `sae-lens>=6.0.0`, `transformer-lens>=2.0.0`, `torch>=2.0.0` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Sparse Autoencoders`, `SAE`, `Mechanistic Interpretability`, `Feature Discovery`, `Superposition` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# SAELens: Sparse Autoencoders for Mechanistic Interpretability
|
||||
|
||||
SAELens is the primary library for training and analyzing Sparse Autoencoders (SAEs) - a technique for decomposing polysemantic neural network activations into sparse, interpretable features. Based on Anthropic's groundbreaking research on monosemanticity.
|
||||
|
||||
**GitHub**: [jbloomAus/SAELens](https://github.com/jbloomAus/SAELens) (1,100+ stars)
|
||||
|
||||
## The Problem: Polysemanticity & Superposition
|
||||
|
||||
Individual neurons in neural networks are **polysemantic** - they activate in multiple, semantically distinct contexts. This happens because models use **superposition** to represent more features than they have neurons, making interpretability difficult.
|
||||
|
||||
**SAEs solve this** by decomposing dense activations into sparse, monosemantic features - typically only a small number of features activate for any given input, and each feature corresponds to an interpretable concept.
|
||||
|
||||
## When to Use SAELens
|
||||
|
||||
**Use SAELens when you need to:**
|
||||
- Discover interpretable features in model activations
|
||||
- Understand what concepts a model has learned
|
||||
- Study superposition and feature geometry
|
||||
- Perform feature-based steering or ablation
|
||||
- Analyze safety-relevant features (deception, bias, harmful content)
|
||||
|
||||
**Consider alternatives when:**
|
||||
- You need basic activation analysis → Use **TransformerLens** directly
|
||||
- You want causal intervention experiments → Use **pyvene** or **TransformerLens**
|
||||
- You need production steering → Consider direct activation engineering
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip install sae-lens
|
||||
```
|
||||
|
||||
Requirements: Python 3.10+, transformer-lens>=2.0.0
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### What SAEs Learn
|
||||
|
||||
SAEs are trained to reconstruct model activations through a sparse bottleneck:
|
||||
|
||||
```
|
||||
Input Activation → Encoder → Sparse Features → Decoder → Reconstructed Activation
|
||||
(d_model) ↓ (d_sae >> d_model) ↓ (d_model)
|
||||
sparsity reconstruction
|
||||
penalty loss
|
||||
```
|
||||
|
||||
**Loss Function**: `MSE(original, reconstructed) + L1_coefficient × L1(features)`
|
||||
|
||||
### Key Validation (Anthropic Research)
|
||||
|
||||
In "Towards Monosemanticity", human evaluators found **70% of SAE features genuinely interpretable**. Features discovered include:
|
||||
- DNA sequences, legal language, HTTP requests
|
||||
- Hebrew text, nutrition statements, code syntax
|
||||
- Sentiment, named entities, grammatical structures
|
||||
|
||||
## Workflow 1: Loading and Analyzing Pre-trained SAEs
|
||||
|
||||
### Step-by-Step
|
||||
|
||||
```python
|
||||
from transformer_lens import HookedTransformer
|
||||
from sae_lens import SAE
|
||||
|
||||
# 1. Load model and pre-trained SAE
|
||||
model = HookedTransformer.from_pretrained("gpt2-small", device="cuda")
|
||||
# In sae-lens v6, SAE.from_pretrained() returns JUST the SAE (not a tuple).
|
||||
sae = SAE.from_pretrained(
|
||||
release="gpt2-small-res-jb",
|
||||
sae_id="blocks.8.hook_resid_pre",
|
||||
device="cuda"
|
||||
)
|
||||
# If you also need the cfg dict and feature sparsity, use:
|
||||
# sae, cfg_dict, sparsity = SAE.from_pretrained_with_cfg_and_sparsity(...)
|
||||
|
||||
# 2. Get model activations
|
||||
tokens = model.to_tokens("The capital of France is Paris")
|
||||
_, cache = model.run_with_cache(tokens)
|
||||
activations = cache["resid_pre", 8] # [batch, pos, d_model]
|
||||
|
||||
# 3. Encode to SAE features
|
||||
sae_features = sae.encode(activations) # [batch, pos, d_sae]
|
||||
print(f"Active features: {(sae_features > 0).sum()}")
|
||||
|
||||
# 4. Find top features for each position
|
||||
for pos in range(tokens.shape[1]):
|
||||
top_features = sae_features[0, pos].topk(5)
|
||||
token = model.to_str_tokens(tokens[0, pos:pos+1])[0]
|
||||
print(f"Token '{token}': features {top_features.indices.tolist()}")
|
||||
|
||||
# 5. Reconstruct activations
|
||||
reconstructed = sae.decode(sae_features)
|
||||
reconstruction_error = (activations - reconstructed).norm()
|
||||
```
|
||||
|
||||
### Available Pre-trained SAEs
|
||||
|
||||
| Release | Model | Layers |
|
||||
|---------|-------|--------|
|
||||
| `gpt2-small-res-jb` | GPT-2 Small | Multiple residual streams |
|
||||
| `gemma-2b-res` | Gemma 2B | Residual streams |
|
||||
| Various on HuggingFace | Search tag `saelens` | Various |
|
||||
|
||||
### Checklist
|
||||
- [ ] Load model with TransformerLens
|
||||
- [ ] Load matching SAE for target layer
|
||||
- [ ] Encode activations to sparse features
|
||||
- [ ] Identify top-activating features per token
|
||||
- [ ] Validate reconstruction quality
|
||||
|
||||
## Workflow 2: Training a Custom SAE
|
||||
|
||||
### Step-by-Step
|
||||
|
||||
```python
|
||||
from sae_lens import (
|
||||
LanguageModelSAETrainingRunner,
|
||||
LanguageModelSAERunnerConfig,
|
||||
StandardTrainingSAEConfig,
|
||||
LoggingConfig,
|
||||
)
|
||||
|
||||
# 1. Configure training (v6 uses a NESTED config: SAE-specific options live in a
|
||||
# `sae=` sub-config, and logging options live in a `logger=` sub-config).
|
||||
# Note: `architecture`, `d_sae`, `l1_coefficient` etc. are now on the SAE sub-config,
|
||||
# and legacy flat options like `hook_layer`, `activation_fn`, `log_to_wandb` were removed.
|
||||
cfg = LanguageModelSAERunnerConfig(
|
||||
# SAE architecture + sparsity (nested)
|
||||
sae=StandardTrainingSAEConfig(
|
||||
d_in=768, # Model dimension
|
||||
d_sae=768 * 8, # Expansion factor of 8
|
||||
l1_coefficient=8e-5, # Sparsity penalty
|
||||
apply_b_dec_to_input=True,
|
||||
normalize_activations="expected_average_only_in",
|
||||
),
|
||||
|
||||
# Data-generating function (model + hook point)
|
||||
model_name="gpt2-small",
|
||||
hook_name="blocks.8.hook_resid_pre", # layer is inferred from hook_name (no hook_layer)
|
||||
|
||||
# Training
|
||||
lr=4e-4,
|
||||
l1_warm_up_steps=1000,
|
||||
train_batch_size_tokens=4096,
|
||||
training_tokens=100_000_000,
|
||||
|
||||
# Data
|
||||
dataset_path="monology/pile-uncopyrighted",
|
||||
context_size=128,
|
||||
|
||||
# Logging (nested)
|
||||
logger=LoggingConfig(
|
||||
log_to_wandb=True,
|
||||
wandb_project="sae-training",
|
||||
),
|
||||
|
||||
# Checkpointing
|
||||
checkpoint_path="checkpoints",
|
||||
n_checkpoints=5,
|
||||
)
|
||||
|
||||
# 2. Train
|
||||
trainer = LanguageModelSAETrainingRunner(cfg) # SAETrainingRunner still works as an alias
|
||||
sae = trainer.run()
|
||||
|
||||
# 3. Evaluate
|
||||
print(f"L0 (avg active features): {trainer.metrics['l0']}")
|
||||
print(f"CE Loss Recovered: {trainer.metrics['ce_loss_score']}")
|
||||
```
|
||||
|
||||
> **v6 migration note:** For other SAE types swap the `sae=` sub-config —
|
||||
> `GatedTrainingSAEConfig`, `TopKTrainingSAEConfig` (set `k` directly), or
|
||||
> `JumpReLUTrainingSAEConfig` (uses `l0_coefficient`). Legacy flat options
|
||||
> (`architecture`, `expansion_factor`, `hook_layer`, `activation_fn`/`activation_fn_kwargs`,
|
||||
> `use_ghost_grads`, ghost grads, b_dec/decoder init options) were removed in v6.
|
||||
|
||||
### Key Hyperparameters
|
||||
|
||||
| Parameter | Typical Value | Effect |
|
||||
|-----------|---------------|--------|
|
||||
| `d_sae` | 4-16× d_model | More features, higher capacity |
|
||||
| `l1_coefficient` | 5e-5 to 1e-4 | Higher = sparser, less accurate |
|
||||
| `lr` | 1e-4 to 1e-3 | Standard optimizer LR |
|
||||
| `l1_warm_up_steps` | 500-2000 | Prevents early feature death |
|
||||
|
||||
### Evaluation Metrics
|
||||
|
||||
| Metric | Target | Meaning |
|
||||
|--------|--------|---------|
|
||||
| **L0** | 50-200 | Average active features per token |
|
||||
| **CE Loss Score** | 80-95% | Cross-entropy recovered vs original |
|
||||
| **Dead Features** | <5% | Features that never activate |
|
||||
| **Explained Variance** | >90% | Reconstruction quality |
|
||||
|
||||
### Checklist
|
||||
- [ ] Choose target layer and hook point
|
||||
- [ ] Set expansion factor (d_sae = 4-16× d_model)
|
||||
- [ ] Tune L1 coefficient for desired sparsity
|
||||
- [ ] Enable L1 warm-up to prevent dead features
|
||||
- [ ] Monitor metrics during training (W&B)
|
||||
- [ ] Validate L0 and CE loss recovery
|
||||
- [ ] Check dead feature ratio
|
||||
|
||||
## Workflow 3: Feature Analysis and Steering
|
||||
|
||||
### Analyzing Individual Features
|
||||
|
||||
```python
|
||||
from transformer_lens import HookedTransformer
|
||||
from sae_lens import SAE
|
||||
import torch
|
||||
|
||||
model = HookedTransformer.from_pretrained("gpt2-small", device="cuda")
|
||||
sae = SAE.from_pretrained( # v6 returns just the SAE
|
||||
release="gpt2-small-res-jb",
|
||||
sae_id="blocks.8.hook_resid_pre",
|
||||
device="cuda"
|
||||
)
|
||||
|
||||
# Find what activates a specific feature
|
||||
feature_idx = 1234
|
||||
test_texts = [
|
||||
"The scientist conducted an experiment",
|
||||
"I love chocolate cake",
|
||||
"The code compiles successfully",
|
||||
"Paris is beautiful in spring",
|
||||
]
|
||||
|
||||
for text in test_texts:
|
||||
tokens = model.to_tokens(text)
|
||||
_, cache = model.run_with_cache(tokens)
|
||||
features = sae.encode(cache["resid_pre", 8])
|
||||
activation = features[0, :, feature_idx].max().item()
|
||||
print(f"{activation:.3f}: {text}")
|
||||
```
|
||||
|
||||
### Feature Steering
|
||||
|
||||
```python
|
||||
def steer_with_feature(model, sae, prompt, feature_idx, strength=5.0):
|
||||
"""Add SAE feature direction to residual stream."""
|
||||
tokens = model.to_tokens(prompt)
|
||||
|
||||
# Get feature direction from decoder
|
||||
feature_direction = sae.W_dec[feature_idx] # [d_model]
|
||||
|
||||
def steering_hook(activation, hook):
|
||||
# Add scaled feature direction at all positions
|
||||
activation += strength * feature_direction
|
||||
return activation
|
||||
|
||||
# Generate with steering
|
||||
output = model.generate(
|
||||
tokens,
|
||||
max_new_tokens=50,
|
||||
fwd_hooks=[("blocks.8.hook_resid_pre", steering_hook)]
|
||||
)
|
||||
return model.to_string(output[0])
|
||||
```
|
||||
|
||||
### Feature Attribution
|
||||
|
||||
```python
|
||||
# Which features most affect a specific output?
|
||||
tokens = model.to_tokens("The capital of France is")
|
||||
_, cache = model.run_with_cache(tokens)
|
||||
|
||||
# Get features at final position
|
||||
features = sae.encode(cache["resid_pre", 8])[0, -1] # [d_sae]
|
||||
|
||||
# Get logit attribution per feature
|
||||
# Feature contribution = feature_activation × decoder_weight × unembedding
|
||||
W_dec = sae.W_dec # [d_sae, d_model]
|
||||
W_U = model.W_U # [d_model, vocab]
|
||||
|
||||
# Contribution to "Paris" logit
|
||||
paris_token = model.to_single_token(" Paris")
|
||||
feature_contributions = features * (W_dec @ W_U[:, paris_token])
|
||||
|
||||
top_features = feature_contributions.topk(10)
|
||||
print("Top features for 'Paris' prediction:")
|
||||
for idx, val in zip(top_features.indices, top_features.values):
|
||||
print(f" Feature {idx.item()}: {val.item():.3f}")
|
||||
```
|
||||
|
||||
## Common Issues & Solutions
|
||||
|
||||
> All examples below use the v6 nested config: SAE-specific options go in the `sae=`
|
||||
> sub-config (`StandardTrainingSAEConfig` / `TopKTrainingSAEConfig` / etc.), training
|
||||
> knobs stay on the top-level `LanguageModelSAERunnerConfig`.
|
||||
|
||||
### Issue: High dead feature ratio
|
||||
```python
|
||||
from sae_lens import LanguageModelSAERunnerConfig, StandardTrainingSAEConfig
|
||||
|
||||
# WRONG: no warm-up, features die early
|
||||
cfg = LanguageModelSAERunnerConfig(
|
||||
sae=StandardTrainingSAEConfig(d_in=768, d_sae=768*8, l1_coefficient=1e-4),
|
||||
l1_warm_up_steps=0, # Bad!
|
||||
)
|
||||
|
||||
# RIGHT: warm up the L1 penalty (v6 removed ghost grads; warm-up is the lever now)
|
||||
cfg = LanguageModelSAERunnerConfig(
|
||||
sae=StandardTrainingSAEConfig(d_in=768, d_sae=768*8, l1_coefficient=8e-5),
|
||||
l1_warm_up_steps=1000, # Gradually increase
|
||||
)
|
||||
```
|
||||
|
||||
### Issue: Poor reconstruction (low CE recovery)
|
||||
```python
|
||||
# Reduce sparsity penalty and/or add capacity (both on the SAE sub-config)
|
||||
cfg = LanguageModelSAERunnerConfig(
|
||||
sae=StandardTrainingSAEConfig(
|
||||
d_in=768,
|
||||
d_sae=768 * 16, # More capacity
|
||||
l1_coefficient=5e-5, # Lower = better reconstruction
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
### Issue: Features not interpretable
|
||||
```python
|
||||
from sae_lens import LanguageModelSAERunnerConfig, StandardTrainingSAEConfig, TopKTrainingSAEConfig
|
||||
|
||||
# Increase sparsity (higher L1)
|
||||
cfg = LanguageModelSAERunnerConfig(
|
||||
sae=StandardTrainingSAEConfig(d_in=768, d_sae=768*8, l1_coefficient=1e-4),
|
||||
)
|
||||
# Or use a TopK SAE (k is set directly in v6, not via activation_fn_kwargs)
|
||||
cfg = LanguageModelSAERunnerConfig(
|
||||
sae=TopKTrainingSAEConfig(d_in=768, d_sae=768*8, k=50), # Exactly 50 active features
|
||||
)
|
||||
```
|
||||
|
||||
### Issue: Memory errors during training
|
||||
```python
|
||||
cfg = LanguageModelSAERunnerConfig(
|
||||
sae=StandardTrainingSAEConfig(d_in=768, d_sae=768*8, l1_coefficient=8e-5),
|
||||
train_batch_size_tokens=2048, # Reduce batch size
|
||||
store_batch_size_prompts=4, # Fewer prompts in buffer
|
||||
n_batches_in_buffer=8, # Smaller activation buffer
|
||||
)
|
||||
```
|
||||
|
||||
## Integration with Neuronpedia
|
||||
|
||||
Browse pre-trained SAE features at [neuronpedia.org](https://neuronpedia.org):
|
||||
|
||||
```python
|
||||
# Features are indexed by SAE ID
|
||||
# Example: gpt2-small layer 8 feature 1234
|
||||
# → neuronpedia.org/gpt2-small/8-res-jb/1234
|
||||
```
|
||||
|
||||
## Key Classes Reference
|
||||
|
||||
| Class | Purpose |
|
||||
|-------|---------|
|
||||
| `SAE` | Sparse Autoencoder model |
|
||||
| `LanguageModelSAERunnerConfig` | Top-level training configuration (nests `sae=` and `logger=`) |
|
||||
| `StandardTrainingSAEConfig` / `TopKTrainingSAEConfig` / `GatedTrainingSAEConfig` / `JumpReLUTrainingSAEConfig` | SAE-type-specific sub-configs (v6) |
|
||||
| `LoggingConfig` | Logging/W&B sub-config (v6) |
|
||||
| `LanguageModelSAETrainingRunner` | Training loop manager (alias: `SAETrainingRunner`) |
|
||||
| `ActivationsStore` | Activation collection and batching |
|
||||
| `HookedSAETransformer` | TransformerLens + SAE integration |
|
||||
|
||||
## Reference Documentation
|
||||
|
||||
For detailed API documentation, tutorials, and advanced usage, see the `references/` folder:
|
||||
|
||||
| File | Contents |
|
||||
|------|----------|
|
||||
| [references/README.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\saelens/references/README.md) | Overview and quick start guide |
|
||||
| [references/api.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\saelens/references/api.md) | Complete API reference for SAE, TrainingSAE, configurations |
|
||||
| [references/tutorials.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\saelens/references/tutorials.md) | Step-by-step tutorials for training, analysis, steering |
|
||||
|
||||
## External Resources
|
||||
|
||||
### Tutorials
|
||||
- [Basic Loading & Analysis](https://github.com/jbloomAus/SAELens/blob/main/tutorials/basic_loading_and_analysing.ipynb)
|
||||
- [Training a Sparse Autoencoder](https://github.com/jbloomAus/SAELens/blob/main/tutorials/training_a_sparse_autoencoder.ipynb)
|
||||
- [ARENA SAE Curriculum](https://www.lesswrong.com/posts/LnHowHgmrMbWtpkxx/intro-to-superposition-and-sparse-autoencoders-colab)
|
||||
|
||||
### Papers
|
||||
- [Towards Monosemanticity](https://transformer-circuits.pub/2023/monosemantic-features) - Anthropic (2023)
|
||||
- [Scaling Monosemanticity](https://transformer-circuits.pub/2024/scaling-monosemanticity/) - Anthropic (2024)
|
||||
- [Sparse Autoencoders Find Highly Interpretable Features](https://arxiv.org/abs/2309.08600) - Cunningham et al. (ICLR 2024)
|
||||
|
||||
### Official Documentation
|
||||
- [SAELens Docs](https://jbloomaus.github.io/SAELens/)
|
||||
- [Neuronpedia](https://neuronpedia.org) - Feature browser
|
||||
|
||||
## SAE Architectures
|
||||
|
||||
| Architecture | Description | Use Case |
|
||||
|--------------|-------------|----------|
|
||||
| **Standard** | ReLU + L1 penalty | General purpose |
|
||||
| **Gated** | Learned gating mechanism | Better sparsity control |
|
||||
| **TopK** | Exactly K active features | Consistent sparsity |
|
||||
|
||||
```python
|
||||
from sae_lens import LanguageModelSAERunnerConfig, TopKTrainingSAEConfig
|
||||
|
||||
# TopK SAE (exactly 50 features active) — `k` is set on the SAE sub-config in v6
|
||||
cfg = LanguageModelSAERunnerConfig(
|
||||
sae=TopKTrainingSAEConfig(d_in=768, d_sae=768*8, k=50),
|
||||
)
|
||||
```
|
||||
@@ -0,0 +1,237 @@
|
||||
---
|
||||
title: "Simpo — Reference-free preference alignment, simpler than DPO"
|
||||
sidebar_label: "Simpo"
|
||||
description: "Reference-free preference alignment, simpler than DPO"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Simpo
|
||||
|
||||
Reference-free preference alignment, simpler than DPO.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/simpo` |
|
||||
| Path | `optional-skills/mlops\simpo` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `torch`, `transformers`, `datasets`, `trl`, `accelerate` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Post-Training`, `SimPO`, `Preference Optimization`, `Alignment`, `DPO Alternative`, `Reference-Free`, `LLM Alignment`, `Efficient Training` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# SimPO - Simple Preference Optimization
|
||||
|
||||
## Quick start
|
||||
|
||||
SimPO is a reference-free preference optimization method that outperforms DPO without needing a reference model.
|
||||
|
||||
**Installation**:
|
||||
```bash
|
||||
# Create environment
|
||||
conda create -n simpo python=3.10 && conda activate simpo
|
||||
|
||||
# Install PyTorch 2.2.2
|
||||
# Visit: https://pytorch.org/get-started/locally/
|
||||
|
||||
# Install alignment-handbook
|
||||
git clone https://github.com/huggingface/alignment-handbook.git
|
||||
cd alignment-handbook
|
||||
python -m pip install .
|
||||
|
||||
# Install Flash Attention 2
|
||||
python -m pip install flash-attn --no-build-isolation
|
||||
```
|
||||
|
||||
**Training** (Mistral 7B):
|
||||
```bash
|
||||
ACCELERATE_LOG_LEVEL=info accelerate launch \
|
||||
--config_file accelerate_configs/deepspeed_zero3.yaml \
|
||||
scripts/run_simpo.py \
|
||||
training_configs/mistral-7b-base-simpo.yaml
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: Train from base model (Mistral 7B)
|
||||
|
||||
**Config** (`mistral-7b-base-simpo.yaml`):
|
||||
```yaml
|
||||
# Model
|
||||
model_name_or_path: mistralai/Mistral-7B-v0.1
|
||||
torch_dtype: bfloat16
|
||||
|
||||
# Dataset
|
||||
dataset_mixer:
|
||||
HuggingFaceH4/ultrafeedback_binarized: 1.0
|
||||
dataset_splits:
|
||||
- train_prefs
|
||||
- test_prefs
|
||||
|
||||
# SimPO hyperparameters
|
||||
beta: 2.0 # Reward scaling (2.0-10.0)
|
||||
gamma_beta_ratio: 0.5 # Target margin (0-1)
|
||||
loss_type: sigmoid # sigmoid or hinge
|
||||
sft_weight: 0.0 # Optional SFT regularization
|
||||
|
||||
# Training
|
||||
learning_rate: 5e-7 # Critical: 3e-7 to 1e-6
|
||||
num_train_epochs: 1
|
||||
per_device_train_batch_size: 1
|
||||
gradient_accumulation_steps: 8
|
||||
|
||||
# Output
|
||||
output_dir: ./outputs/mistral-7b-simpo
|
||||
```
|
||||
|
||||
**Launch training**:
|
||||
```bash
|
||||
accelerate launch --config_file accelerate_configs/deepspeed_zero3.yaml \
|
||||
scripts/run_simpo.py training_configs/mistral-7b-base-simpo.yaml
|
||||
```
|
||||
|
||||
### Workflow 2: Fine-tune instruct model (Llama 3 8B)
|
||||
|
||||
**Config** (`llama3-8b-instruct-simpo.yaml`):
|
||||
```yaml
|
||||
model_name_or_path: meta-llama/Meta-Llama-3-8B-Instruct
|
||||
|
||||
dataset_mixer:
|
||||
argilla/ultrafeedback-binarized-preferences-cleaned: 1.0
|
||||
|
||||
beta: 2.5
|
||||
gamma_beta_ratio: 0.5
|
||||
learning_rate: 5e-7
|
||||
sft_weight: 0.1 # Add SFT loss to preserve capabilities
|
||||
|
||||
num_train_epochs: 1
|
||||
per_device_train_batch_size: 2
|
||||
gradient_accumulation_steps: 4
|
||||
output_dir: ./outputs/llama3-8b-simpo
|
||||
```
|
||||
|
||||
**Launch**:
|
||||
```bash
|
||||
accelerate launch --config_file accelerate_configs/deepspeed_zero3.yaml \
|
||||
scripts/run_simpo.py training_configs/llama3-8b-instruct-simpo.yaml
|
||||
```
|
||||
|
||||
### Workflow 3: Reasoning-intensive tasks (lower LR)
|
||||
|
||||
**For math/code tasks**:
|
||||
```yaml
|
||||
model_name_or_path: deepseek-ai/deepseek-math-7b-base
|
||||
|
||||
dataset_mixer:
|
||||
argilla/distilabel-math-preference-dpo: 1.0
|
||||
|
||||
beta: 5.0 # Higher for stronger signal
|
||||
gamma_beta_ratio: 0.7 # Larger margin
|
||||
learning_rate: 3e-7 # Lower LR for reasoning
|
||||
sft_weight: 0.0
|
||||
|
||||
num_train_epochs: 1
|
||||
per_device_train_batch_size: 1
|
||||
gradient_accumulation_steps: 16
|
||||
```
|
||||
|
||||
## When to use vs alternatives
|
||||
|
||||
**Use SimPO when**:
|
||||
- Want simpler training than DPO (no reference model)
|
||||
- Have preference data (chosen/rejected pairs)
|
||||
- Need better performance than DPO
|
||||
- Limited compute resources
|
||||
- Single-node training sufficient
|
||||
|
||||
**Algorithm selection**:
|
||||
- **SimPO**: Simplest, best performance, no reference model
|
||||
- **DPO**: Need reference model baseline, more conservative
|
||||
- **PPO**: Maximum control, need reward model, complex setup
|
||||
- **GRPO**: Memory-efficient RL, no critic
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **OpenRLHF**: Multi-node distributed training, PPO/GRPO
|
||||
- **TRL**: Need multiple methods in one framework
|
||||
- **DPO**: Established baseline comparison
|
||||
|
||||
## Common issues
|
||||
|
||||
**Issue: Loss divergence**
|
||||
|
||||
Reduce learning rate:
|
||||
```yaml
|
||||
learning_rate: 3e-7 # Reduce from 5e-7
|
||||
```
|
||||
|
||||
Reduce beta:
|
||||
```yaml
|
||||
beta: 1.0 # Reduce from 2.0
|
||||
```
|
||||
|
||||
**Issue: Model forgets capabilities**
|
||||
|
||||
Add SFT regularization:
|
||||
```yaml
|
||||
sft_weight: 0.1 # Add SFT loss component
|
||||
```
|
||||
|
||||
**Issue: Poor preference separation**
|
||||
|
||||
Increase beta and margin:
|
||||
```yaml
|
||||
beta: 5.0 # Increase from 2.0
|
||||
gamma_beta_ratio: 0.8 # Increase from 0.5
|
||||
```
|
||||
|
||||
**Issue: OOM during training**
|
||||
|
||||
Reduce batch size:
|
||||
```yaml
|
||||
per_device_train_batch_size: 1
|
||||
gradient_accumulation_steps: 16 # Maintain effective batch
|
||||
```
|
||||
|
||||
Enable gradient checkpointing:
|
||||
```yaml
|
||||
gradient_checkpointing: true
|
||||
```
|
||||
|
||||
## Advanced topics
|
||||
|
||||
**Loss functions**: See [references/loss-functions.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\simpo/references/loss-functions.md) for sigmoid vs hinge loss, mathematical formulations, and when to use each.
|
||||
|
||||
**Hyperparameter tuning**: See [references/hyperparameters.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\simpo/references/hyperparameters.md) for beta, gamma, learning rate selection guide, and model-size-specific recommendations.
|
||||
|
||||
**Dataset preparation**: See [references/datasets.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\simpo/references/datasets.md) for preference data formats, quality filtering, and custom dataset creation.
|
||||
|
||||
## Hardware requirements
|
||||
|
||||
- **GPU**: NVIDIA A100/H100 recommended
|
||||
- **VRAM**:
|
||||
- 7B model: 1× A100 40GB (DeepSpeed ZeRO-3)
|
||||
- 8B model: 2× A100 40GB
|
||||
- 70B model: 8× A100 80GB
|
||||
- **Single-node**: DeepSpeed ZeRO-3 sufficient
|
||||
- **Mixed precision**: BF16 recommended
|
||||
|
||||
**Memory optimization**:
|
||||
- DeepSpeed ZeRO-3 (default config)
|
||||
- Gradient checkpointing
|
||||
- Flash Attention 2
|
||||
|
||||
## Resources
|
||||
|
||||
- Paper: https://arxiv.org/abs/2405.14734 (NeurIPS 2024)
|
||||
- GitHub: https://github.com/princeton-nlp/SimPO
|
||||
- Models: https://huggingface.co/princeton-nlp
|
||||
- Alignment Handbook: https://github.com/huggingface/alignment-handbook
|
||||
@@ -0,0 +1,486 @@
|
||||
---
|
||||
title: "Slime — RL post-training for LLMs with Megatron and SGLang"
|
||||
sidebar_label: "Slime"
|
||||
description: "RL post-training for LLMs with Megatron and SGLang"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Slime
|
||||
|
||||
RL post-training for LLMs with Megatron and SGLang.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/slime` |
|
||||
| Path | `optional-skills/mlops\slime` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `sglang-router>=0.2.3`, `ray`, `torch>=2.0.0`, `transformers>=4.40.0` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Reinforcement Learning`, `Megatron-LM`, `SGLang`, `GRPO`, `Post-Training`, `GLM` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# slime: LLM Post-Training Framework for RL Scaling
|
||||
|
||||
slime is an LLM post-training framework from Tsinghua's THUDM team, powering GLM-4.5, GLM-4.6, and GLM-4.7. It connects Megatron-LM for training with SGLang for high-throughput rollout generation.
|
||||
|
||||
## When to Use slime
|
||||
|
||||
**Choose slime when you need:**
|
||||
- Megatron-LM native training with SGLang inference
|
||||
- Custom data generation workflows with flexible data buffers
|
||||
- Training GLM, Qwen3, DeepSeek V3, or Llama 3 models
|
||||
- Research-grade framework with production backing (Z.ai)
|
||||
|
||||
**Consider alternatives when:**
|
||||
- You need enterprise-grade stability features → use **miles**
|
||||
- You want flexible backend swapping → use **verl**
|
||||
- You need PyTorch-native abstractions → use **torchforge**
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Training**: Megatron-LM with full parallelism support (TP, PP, DP, SP)
|
||||
- **Rollout**: SGLang-based high-throughput generation with router
|
||||
- **Data Buffer**: Flexible prompt management and sample storage
|
||||
- **Models**: GLM-4.x, Qwen3, DeepSeek V3/R1, Llama 3
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
<!-- ascii-guard-ignore -->
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Data Buffer │
|
||||
│ - Prompt initialization and management │
|
||||
│ - Custom data generation and filtering │
|
||||
│ - Rollout sample storage │
|
||||
└─────────────┬───────────────────────────┬───────────────┘
|
||||
│ │
|
||||
┌─────────────▼───────────┐ ┌─────────────▼───────────────┐
|
||||
│ Training (Megatron-LM) │ │ Rollout (SGLang + Router) │
|
||||
│ - Actor model training │ │ - Response generation │
|
||||
│ - Critic (optional) │ │ - Reward/verifier output │
|
||||
│ - Weight sync to rollout│ │ - Multi-turn support │
|
||||
└─────────────────────────┘ └─────────────────────────────┘
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Recommended: Docker
|
||||
docker pull slimerl/slime:latest
|
||||
docker run --rm --gpus all --ipc=host --shm-size=16g \
|
||||
-it slimerl/slime:latest /bin/bash
|
||||
|
||||
# Inside container
|
||||
cd /root/slime && pip install -e . --no-deps
|
||||
```
|
||||
|
||||
### From Source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/THUDM/slime.git
|
||||
cd slime
|
||||
pip install -r requirements.txt
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
## Quick Start: GRPO Training
|
||||
|
||||
```bash
|
||||
# Source model configuration
|
||||
source scripts/models/qwen3-4B.sh
|
||||
|
||||
# Launch training
|
||||
python train.py \
|
||||
--actor-num-nodes 1 \
|
||||
--actor-num-gpus-per-node 4 \
|
||||
--rollout-num-gpus 4 \
|
||||
--advantage-estimator grpo \
|
||||
--use-kl-loss --kl-loss-coef 0.001 \
|
||||
--rollout-batch-size 32 \
|
||||
--n-samples-per-prompt 8 \
|
||||
--global-batch-size 256 \
|
||||
--num-rollout 3000 \
|
||||
--prompt-data /path/to/data.jsonl \
|
||||
${MODEL_ARGS[@]} ${CKPT_ARGS[@]}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Workflow 1: Standard GRPO Training
|
||||
|
||||
Use this workflow for training reasoning models with group-relative advantages.
|
||||
|
||||
### Prerequisites Checklist
|
||||
- [ ] Docker environment or Megatron-LM + SGLang installed
|
||||
- [ ] Model checkpoint (HuggingFace or Megatron format)
|
||||
- [ ] Training data in JSONL format
|
||||
|
||||
### Step 1: Prepare Data
|
||||
|
||||
```python
|
||||
# data.jsonl format
|
||||
{"prompt": "What is 2 + 2?", "label": "4"}
|
||||
{"prompt": "Solve: 3x = 12", "label": "x = 4"}
|
||||
```
|
||||
|
||||
Or with chat format:
|
||||
```python
|
||||
{
|
||||
"prompt": [
|
||||
{"role": "system", "content": "You are a math tutor."},
|
||||
{"role": "user", "content": "What is 15 + 27?"}
|
||||
],
|
||||
"label": "42"
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2: Configure Model
|
||||
|
||||
Choose a pre-configured model script:
|
||||
|
||||
```bash
|
||||
# List available models
|
||||
ls scripts/models/
|
||||
# glm4-9B.sh, qwen3-4B.sh, qwen3-30B-A3B.sh, deepseek-v3.sh, llama3-8B.sh, ...
|
||||
|
||||
# Source your model
|
||||
source scripts/models/qwen3-4B.sh
|
||||
```
|
||||
|
||||
### Step 3: Launch Training
|
||||
|
||||
```bash
|
||||
python train.py \
|
||||
--actor-num-nodes 1 \
|
||||
--actor-num-gpus-per-node 8 \
|
||||
--rollout-num-gpus 8 \
|
||||
--advantage-estimator grpo \
|
||||
--use-kl-loss \
|
||||
--kl-loss-coef 0.001 \
|
||||
--prompt-data /path/to/train.jsonl \
|
||||
--input-key prompt \
|
||||
--label-key label \
|
||||
--apply-chat-template \
|
||||
--rollout-batch-size 32 \
|
||||
--n-samples-per-prompt 8 \
|
||||
--global-batch-size 256 \
|
||||
--num-rollout 3000 \
|
||||
--save-interval 100 \
|
||||
--eval-interval 50 \
|
||||
${MODEL_ARGS[@]}
|
||||
```
|
||||
|
||||
### Step 4: Monitor Training
|
||||
- [ ] Check TensorBoard: `tensorboard --logdir outputs/`
|
||||
- [ ] Verify reward curves are increasing
|
||||
- [ ] Monitor GPU utilization across nodes
|
||||
|
||||
---
|
||||
|
||||
## Workflow 2: Asynchronous Training
|
||||
|
||||
Use async mode for higher throughput by overlapping rollout and training.
|
||||
|
||||
### When to Use Async
|
||||
- Large models with long generation times
|
||||
- High GPU idle time in synchronous mode
|
||||
- Sufficient memory for buffering
|
||||
|
||||
### Launch Async Training
|
||||
|
||||
```bash
|
||||
python train_async.py \
|
||||
--actor-num-nodes 1 \
|
||||
--actor-num-gpus-per-node 8 \
|
||||
--rollout-num-gpus 8 \
|
||||
--advantage-estimator grpo \
|
||||
--async-buffer-size 4 \
|
||||
--prompt-data /path/to/train.jsonl \
|
||||
${MODEL_ARGS[@]}
|
||||
```
|
||||
|
||||
### Async-Specific Parameters
|
||||
|
||||
```bash
|
||||
--async-buffer-size 4 # Number of rollouts to buffer
|
||||
--update-weights-interval 2 # Sync weights every N rollouts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Workflow 3: Multi-Turn Agentic Training
|
||||
|
||||
Use this workflow for training agents with tool use or multi-step reasoning.
|
||||
|
||||
### Prerequisites
|
||||
- [ ] Custom generate function for multi-turn logic
|
||||
- [ ] Tool/environment interface
|
||||
|
||||
### Step 1: Define Custom Generate Function
|
||||
|
||||
```python
|
||||
# custom_generate.py
|
||||
async def custom_generate(args, samples, evaluation=False):
|
||||
"""Multi-turn generation with tool calling."""
|
||||
for sample in samples:
|
||||
conversation = sample.prompt
|
||||
|
||||
for turn in range(args.max_turns):
|
||||
# Generate response
|
||||
response = await generate_single(conversation)
|
||||
|
||||
# Check for tool call
|
||||
tool_call = extract_tool_call(response)
|
||||
if tool_call:
|
||||
tool_result = execute_tool(tool_call)
|
||||
conversation.append({"role": "assistant", "content": response})
|
||||
conversation.append({"role": "tool", "content": tool_result})
|
||||
else:
|
||||
break
|
||||
|
||||
sample.response = response
|
||||
sample.reward = compute_reward(sample)
|
||||
|
||||
return samples
|
||||
```
|
||||
|
||||
### Step 2: Launch with Custom Function
|
||||
|
||||
```bash
|
||||
python train.py \
|
||||
--custom-generate-function-path custom_generate.py \
|
||||
--max-turns 5 \
|
||||
--prompt-data /path/to/agent_data.jsonl \
|
||||
${MODEL_ARGS[@]}
|
||||
```
|
||||
|
||||
See `examples/search-r1/` for a complete multi-turn search example.
|
||||
|
||||
---
|
||||
|
||||
## Configuration Reference
|
||||
|
||||
### Three Argument Categories
|
||||
|
||||
slime uses three types of arguments:
|
||||
|
||||
**1. Megatron Arguments** (passed directly):
|
||||
```bash
|
||||
--tensor-model-parallel-size 2
|
||||
--pipeline-model-parallel-size 1
|
||||
--num-layers 32
|
||||
--hidden-size 4096
|
||||
```
|
||||
|
||||
**2. SGLang Arguments** (prefixed with `--sglang-`):
|
||||
```bash
|
||||
--sglang-mem-fraction-static 0.8
|
||||
--sglang-context-length 8192
|
||||
--sglang-log-level INFO
|
||||
```
|
||||
|
||||
**3. slime Arguments**:
|
||||
```bash
|
||||
# Resource allocation
|
||||
--actor-num-nodes 1
|
||||
--actor-num-gpus-per-node 8
|
||||
--rollout-num-gpus 8
|
||||
--colocate # Share GPUs between training/inference
|
||||
|
||||
# Data
|
||||
--prompt-data /path/to/data.jsonl
|
||||
--input-key prompt
|
||||
--label-key label
|
||||
|
||||
# Training loop
|
||||
--num-rollout 3000
|
||||
--rollout-batch-size 32
|
||||
--n-samples-per-prompt 8
|
||||
--global-batch-size 256
|
||||
|
||||
# Algorithm
|
||||
--advantage-estimator grpo # or: gspo, ppo, reinforce_plus_plus
|
||||
--use-kl-loss
|
||||
--kl-loss-coef 0.001
|
||||
```
|
||||
|
||||
### Key Constraints
|
||||
|
||||
```
|
||||
rollout_batch_size × n_samples_per_prompt = global_batch_size × num_steps_per_rollout
|
||||
```
|
||||
|
||||
Example: 32 × 8 = 256 × 1
|
||||
|
||||
---
|
||||
|
||||
## Data Buffer System
|
||||
|
||||
slime's data buffer enables flexible data management:
|
||||
|
||||
### Basic Data Source
|
||||
|
||||
```python
|
||||
class RolloutDataSource:
|
||||
def get_samples(self, num_samples):
|
||||
"""Fetch prompts from dataset."""
|
||||
return self.dataset.sample(num_samples)
|
||||
|
||||
def add_samples(self, samples):
|
||||
"""Called after generation (no-op by default)."""
|
||||
pass
|
||||
```
|
||||
|
||||
### Buffered Data Source (Off-Policy)
|
||||
|
||||
```python
|
||||
class RolloutDataSourceWithBuffer(RolloutDataSource):
|
||||
def __init__(self):
|
||||
self.buffer = []
|
||||
|
||||
def add_samples(self, samples):
|
||||
"""Store generated samples for reuse."""
|
||||
self.buffer.extend(samples)
|
||||
|
||||
def buffer_filter(self, args, buffer, num_samples):
|
||||
"""Custom selection logic (prioritized, stratified, etc.)."""
|
||||
return select_best(buffer, num_samples)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Common Issues and Solutions
|
||||
|
||||
### Issue: SGLang Engine Crash
|
||||
|
||||
**Symptoms**: Inference engine dies mid-training
|
||||
|
||||
**Solutions**:
|
||||
```bash
|
||||
# Enable fault tolerance
|
||||
--use-fault-tolerance
|
||||
|
||||
# Increase memory allocation
|
||||
--sglang-mem-fraction-static 0.85
|
||||
|
||||
# Reduce batch size
|
||||
--rollout-batch-size 16
|
||||
```
|
||||
|
||||
### Issue: Weight Sync Timeout
|
||||
|
||||
**Symptoms**: Training hangs after rollout
|
||||
|
||||
**Solutions**:
|
||||
```bash
|
||||
# Increase sync interval
|
||||
--update-weights-interval 5
|
||||
|
||||
# Use colocated mode (no network transfer)
|
||||
--colocate
|
||||
```
|
||||
|
||||
### Issue: OOM During Training
|
||||
|
||||
**Symptoms**: CUDA OOM in backward pass
|
||||
|
||||
**Solutions**:
|
||||
```bash
|
||||
# Enable gradient checkpointing
|
||||
--recompute-activations
|
||||
|
||||
# Reduce micro-batch size
|
||||
--micro-batch-size 1
|
||||
|
||||
# Enable sequence parallelism
|
||||
--sequence-parallel
|
||||
```
|
||||
|
||||
### Issue: Slow Data Loading
|
||||
|
||||
**Symptoms**: GPU idle during data fetch
|
||||
|
||||
**Solutions**:
|
||||
```bash
|
||||
# Increase data workers
|
||||
--num-data-workers 4
|
||||
|
||||
# Use streaming dataset
|
||||
--streaming-data
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Supported Models
|
||||
|
||||
| Model Family | Configurations |
|
||||
|--------------|----------------|
|
||||
| GLM | GLM-4.5, GLM-4.6, GLM-4.7, GLM-Z1-9B |
|
||||
| Qwen | Qwen3 (4B, 8B, 30B-A3B), Qwen3-MoE, Qwen2.5 |
|
||||
| DeepSeek | V3, V3.1, R1 |
|
||||
| Llama | Llama 3 (8B, 70B) |
|
||||
| Others | Kimi K2, Moonlight-16B |
|
||||
|
||||
Each model has pre-configured scripts in `scripts/models/`.
|
||||
|
||||
---
|
||||
|
||||
## Advanced Topics
|
||||
|
||||
### Co-location Mode
|
||||
|
||||
Share GPUs between training and inference to reduce memory:
|
||||
|
||||
```bash
|
||||
python train.py \
|
||||
--colocate \
|
||||
--actor-num-gpus-per-node 8 \
|
||||
--sglang-mem-fraction-static 0.4 \
|
||||
${MODEL_ARGS[@]}
|
||||
```
|
||||
|
||||
### Custom Reward Model
|
||||
|
||||
```python
|
||||
# custom_rm.py
|
||||
class CustomRewardModel:
|
||||
def __init__(self, model_path):
|
||||
self.model = load_model(model_path)
|
||||
|
||||
def compute_reward(self, prompts, responses):
|
||||
inputs = self.tokenize(prompts, responses)
|
||||
scores = self.model(inputs)
|
||||
return scores.tolist()
|
||||
```
|
||||
|
||||
```bash
|
||||
--custom-rm-path custom_rm.py
|
||||
```
|
||||
|
||||
### Evaluation Multi-Task
|
||||
|
||||
```bash
|
||||
--eval-prompt-data aime /path/to/aime.jsonl \
|
||||
--eval-prompt-data gsm8k /path/to/gsm8k.jsonl \
|
||||
--n-samples-per-eval-prompt 16
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Resources
|
||||
|
||||
- **Documentation**: https://thudm.github.io/slime/
|
||||
- **GitHub**: https://github.com/THUDM/slime
|
||||
- **Blog**: https://lmsys.org/blog/2025-07-09-slime/
|
||||
- **Examples**: See `examples/` directory for 14+ worked examples
|
||||
@@ -0,0 +1,542 @@
|
||||
---
|
||||
title: "Stable Diffusion — Text-to-image generation, inpainting, and img2img"
|
||||
sidebar_label: "Stable Diffusion"
|
||||
description: "Text-to-image generation, inpainting, and img2img"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Stable Diffusion
|
||||
|
||||
Text-to-image generation, inpainting, and img2img.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/stable-diffusion` |
|
||||
| Path | `optional-skills/mlops\stable-diffusion` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `diffusers>=0.30.0`, `transformers>=4.41.0`, `accelerate>=0.31.0`, `torch>=2.0.0` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Image Generation`, `Stable Diffusion`, `Diffusers`, `Text-to-Image`, `Multimodal`, `Computer Vision` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Stable Diffusion Image Generation
|
||||
|
||||
Guide to generating images with Stable Diffusion using the HuggingFace Diffusers library.
|
||||
|
||||
## When to use Stable Diffusion
|
||||
|
||||
**Use Stable Diffusion when:**
|
||||
- Generating images from text descriptions
|
||||
- Performing image-to-image translation (style transfer, enhancement)
|
||||
- Inpainting (filling in masked regions)
|
||||
- Outpainting (extending images beyond boundaries)
|
||||
- Creating variations of existing images
|
||||
- Building custom image generation workflows
|
||||
|
||||
**Key features:**
|
||||
- **Text-to-Image**: Generate images from natural language prompts
|
||||
- **Image-to-Image**: Transform existing images with text guidance
|
||||
- **Inpainting**: Fill masked regions with context-aware content
|
||||
- **ControlNet**: Add spatial conditioning (edges, poses, depth)
|
||||
- **LoRA Support**: Efficient fine-tuning and style adaptation
|
||||
- **Multiple Models**: SD 1.5, SDXL, SD 3.0, Flux support
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **DALL-E 3**: For API-based generation without GPU
|
||||
- **Midjourney**: For artistic, stylized outputs
|
||||
- **Imagen**: For Google Cloud integration
|
||||
- **Leonardo.ai**: For web-based creative workflows
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
pip install diffusers transformers accelerate torch
|
||||
pip install xformers # Optional: memory-efficient attention
|
||||
```
|
||||
|
||||
### Basic text-to-image
|
||||
|
||||
```python
|
||||
from diffusers import DiffusionPipeline
|
||||
import torch
|
||||
|
||||
# Load pipeline (auto-detects model type)
|
||||
pipe = DiffusionPipeline.from_pretrained(
|
||||
"stable-diffusion-v1-5/stable-diffusion-v1-5",
|
||||
torch_dtype=torch.float16
|
||||
)
|
||||
pipe.to("cuda")
|
||||
|
||||
# Generate image
|
||||
image = pipe(
|
||||
"A serene mountain landscape at sunset, highly detailed",
|
||||
num_inference_steps=50,
|
||||
guidance_scale=7.5
|
||||
).images[0]
|
||||
|
||||
image.save("output.png")
|
||||
```
|
||||
|
||||
### Using SDXL (higher quality)
|
||||
|
||||
```python
|
||||
from diffusers import AutoPipelineForText2Image
|
||||
import torch
|
||||
|
||||
pipe = AutoPipelineForText2Image.from_pretrained(
|
||||
"stabilityai/stable-diffusion-xl-base-1.0",
|
||||
torch_dtype=torch.float16,
|
||||
variant="fp16"
|
||||
)
|
||||
pipe.to("cuda")
|
||||
|
||||
# Enable memory optimization
|
||||
pipe.enable_model_cpu_offload()
|
||||
|
||||
image = pipe(
|
||||
prompt="A futuristic city with flying cars, cinematic lighting",
|
||||
height=1024,
|
||||
width=1024,
|
||||
num_inference_steps=30
|
||||
).images[0]
|
||||
```
|
||||
|
||||
## Architecture overview
|
||||
|
||||
### Three-pillar design
|
||||
|
||||
Diffusers is built around three core components:
|
||||
|
||||
<!-- ascii-guard-ignore -->
|
||||
```
|
||||
Pipeline (orchestration)
|
||||
├── Model (neural networks)
|
||||
│ ├── UNet / Transformer (noise prediction)
|
||||
│ ├── VAE (latent encoding/decoding)
|
||||
│ └── Text Encoder (CLIP/T5)
|
||||
└── Scheduler (denoising algorithm)
|
||||
```
|
||||
<!-- ascii-guard-ignore-end -->
|
||||
|
||||
### Pipeline inference flow
|
||||
|
||||
```
|
||||
Text Prompt → Text Encoder → Text Embeddings
|
||||
↓
|
||||
Random Noise → [Denoising Loop] ← Scheduler
|
||||
↓
|
||||
Predicted Noise
|
||||
↓
|
||||
VAE Decoder → Final Image
|
||||
```
|
||||
|
||||
## Core concepts
|
||||
|
||||
### Pipelines
|
||||
|
||||
Pipelines orchestrate complete workflows:
|
||||
|
||||
| Pipeline | Purpose |
|
||||
|----------|---------|
|
||||
| `StableDiffusionPipeline` | Text-to-image (SD 1.x/2.x) |
|
||||
| `StableDiffusionXLPipeline` | Text-to-image (SDXL) |
|
||||
| `StableDiffusion3Pipeline` | Text-to-image (SD 3.0) |
|
||||
| `FluxPipeline` | Text-to-image (Flux models) |
|
||||
| `StableDiffusionImg2ImgPipeline` | Image-to-image |
|
||||
| `StableDiffusionInpaintPipeline` | Inpainting |
|
||||
|
||||
### Schedulers
|
||||
|
||||
Schedulers control the denoising process:
|
||||
|
||||
| Scheduler | Steps | Quality | Use Case |
|
||||
|-----------|-------|---------|----------|
|
||||
| `EulerDiscreteScheduler` | 20-50 | Good | Default choice |
|
||||
| `EulerAncestralDiscreteScheduler` | 20-50 | Good | More variation |
|
||||
| `DPMSolverMultistepScheduler` | 15-25 | Excellent | Fast, high quality |
|
||||
| `DDIMScheduler` | 50-100 | Good | Deterministic |
|
||||
| `LCMScheduler` | 4-8 | Good | Very fast |
|
||||
| `UniPCMultistepScheduler` | 15-25 | Excellent | Fast convergence |
|
||||
|
||||
### Swapping schedulers
|
||||
|
||||
```python
|
||||
from diffusers import DPMSolverMultistepScheduler
|
||||
|
||||
# Swap for faster generation
|
||||
pipe.scheduler = DPMSolverMultistepScheduler.from_config(
|
||||
pipe.scheduler.config
|
||||
)
|
||||
|
||||
# Now generate with fewer steps
|
||||
image = pipe(prompt, num_inference_steps=20).images[0]
|
||||
```
|
||||
|
||||
## Generation parameters
|
||||
|
||||
### Key parameters
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `prompt` | Required | Text description of desired image |
|
||||
| `negative_prompt` | None | What to avoid in the image |
|
||||
| `num_inference_steps` | 50 | Denoising steps (more = better quality) |
|
||||
| `guidance_scale` | 7.5 | Prompt adherence (7-12 typical) |
|
||||
| `height`, `width` | 512/1024 | Output dimensions (multiples of 8) |
|
||||
| `generator` | None | Torch generator for reproducibility |
|
||||
| `num_images_per_prompt` | 1 | Batch size |
|
||||
|
||||
### Reproducible generation
|
||||
|
||||
```python
|
||||
import torch
|
||||
|
||||
generator = torch.Generator(device="cuda").manual_seed(42)
|
||||
|
||||
image = pipe(
|
||||
prompt="A cat wearing a top hat",
|
||||
generator=generator,
|
||||
num_inference_steps=50
|
||||
).images[0]
|
||||
```
|
||||
|
||||
### Negative prompts
|
||||
|
||||
```python
|
||||
image = pipe(
|
||||
prompt="Professional photo of a dog in a garden",
|
||||
negative_prompt="blurry, low quality, distorted, ugly, bad anatomy",
|
||||
guidance_scale=7.5
|
||||
).images[0]
|
||||
```
|
||||
|
||||
## Image-to-image
|
||||
|
||||
Transform existing images with text guidance:
|
||||
|
||||
```python
|
||||
from diffusers import AutoPipelineForImage2Image
|
||||
from PIL import Image
|
||||
|
||||
pipe = AutoPipelineForImage2Image.from_pretrained(
|
||||
"stable-diffusion-v1-5/stable-diffusion-v1-5",
|
||||
torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
|
||||
init_image = Image.open("input.jpg").resize((512, 512))
|
||||
|
||||
image = pipe(
|
||||
prompt="A watercolor painting of the scene",
|
||||
image=init_image,
|
||||
strength=0.75, # How much to transform (0-1)
|
||||
num_inference_steps=50
|
||||
).images[0]
|
||||
```
|
||||
|
||||
## Inpainting
|
||||
|
||||
Fill masked regions:
|
||||
|
||||
```python
|
||||
from diffusers import AutoPipelineForInpainting
|
||||
from PIL import Image
|
||||
|
||||
pipe = AutoPipelineForInpainting.from_pretrained(
|
||||
"runwayml/stable-diffusion-inpainting",
|
||||
torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
|
||||
image = Image.open("photo.jpg")
|
||||
mask = Image.open("mask.png") # White = inpaint region
|
||||
|
||||
result = pipe(
|
||||
prompt="A red car parked on the street",
|
||||
image=image,
|
||||
mask_image=mask,
|
||||
num_inference_steps=50
|
||||
).images[0]
|
||||
```
|
||||
|
||||
## ControlNet
|
||||
|
||||
Add spatial conditioning for precise control:
|
||||
|
||||
```python
|
||||
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
|
||||
import torch
|
||||
|
||||
# Load ControlNet for edge conditioning
|
||||
controlnet = ControlNetModel.from_pretrained(
|
||||
"lllyasviel/control_v11p_sd15_canny",
|
||||
torch_dtype=torch.float16
|
||||
)
|
||||
|
||||
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
||||
"stable-diffusion-v1-5/stable-diffusion-v1-5",
|
||||
controlnet=controlnet,
|
||||
torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
|
||||
# Use Canny edge image as control
|
||||
control_image = get_canny_image(input_image)
|
||||
|
||||
image = pipe(
|
||||
prompt="A beautiful house in the style of Van Gogh",
|
||||
image=control_image,
|
||||
num_inference_steps=30
|
||||
).images[0]
|
||||
```
|
||||
|
||||
### Available ControlNets
|
||||
|
||||
| ControlNet | Input Type | Use Case |
|
||||
|------------|------------|----------|
|
||||
| `canny` | Edge maps | Preserve structure |
|
||||
| `openpose` | Pose skeletons | Human poses |
|
||||
| `depth` | Depth maps | 3D-aware generation |
|
||||
| `normal` | Normal maps | Surface details |
|
||||
| `mlsd` | Line segments | Architectural lines |
|
||||
| `scribble` | Rough sketches | Sketch-to-image |
|
||||
|
||||
## LoRA adapters
|
||||
|
||||
Load fine-tuned style adapters:
|
||||
|
||||
```python
|
||||
from diffusers import DiffusionPipeline
|
||||
|
||||
pipe = DiffusionPipeline.from_pretrained(
|
||||
"stable-diffusion-v1-5/stable-diffusion-v1-5",
|
||||
torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
|
||||
# Load LoRA weights
|
||||
pipe.load_lora_weights("path/to/lora", weight_name="style.safetensors")
|
||||
|
||||
# Generate with LoRA style
|
||||
image = pipe("A portrait in the trained style").images[0]
|
||||
|
||||
# Adjust LoRA strength
|
||||
pipe.fuse_lora(lora_scale=0.8)
|
||||
|
||||
# Unload LoRA
|
||||
pipe.unload_lora_weights()
|
||||
```
|
||||
|
||||
### Multiple LoRAs
|
||||
|
||||
```python
|
||||
# Load multiple LoRAs
|
||||
pipe.load_lora_weights("lora1", adapter_name="style")
|
||||
pipe.load_lora_weights("lora2", adapter_name="character")
|
||||
|
||||
# Set weights for each
|
||||
pipe.set_adapters(["style", "character"], adapter_weights=[0.7, 0.5])
|
||||
|
||||
image = pipe("A portrait").images[0]
|
||||
```
|
||||
|
||||
## Memory optimization
|
||||
|
||||
### Enable CPU offloading
|
||||
|
||||
```python
|
||||
# Model CPU offload - moves models to CPU when not in use
|
||||
pipe.enable_model_cpu_offload()
|
||||
|
||||
# Sequential CPU offload - more aggressive, slower
|
||||
pipe.enable_sequential_cpu_offload()
|
||||
```
|
||||
|
||||
### Attention slicing
|
||||
|
||||
```python
|
||||
# Reduce memory by computing attention in chunks
|
||||
pipe.enable_attention_slicing()
|
||||
|
||||
# Or specific chunk size
|
||||
pipe.enable_attention_slicing("max")
|
||||
```
|
||||
|
||||
### xFormers memory-efficient attention
|
||||
|
||||
```python
|
||||
# Requires xformers package
|
||||
pipe.enable_xformers_memory_efficient_attention()
|
||||
```
|
||||
|
||||
### VAE slicing for large images
|
||||
|
||||
```python
|
||||
# Decode latents in tiles for large images
|
||||
pipe.enable_vae_slicing()
|
||||
pipe.enable_vae_tiling()
|
||||
```
|
||||
|
||||
## Model variants
|
||||
|
||||
### Loading different precisions
|
||||
|
||||
```python
|
||||
# FP16 (recommended for GPU)
|
||||
pipe = DiffusionPipeline.from_pretrained(
|
||||
"model-id",
|
||||
torch_dtype=torch.float16,
|
||||
variant="fp16"
|
||||
)
|
||||
|
||||
# BF16 (better precision, requires Ampere+ GPU)
|
||||
pipe = DiffusionPipeline.from_pretrained(
|
||||
"model-id",
|
||||
torch_dtype=torch.bfloat16
|
||||
)
|
||||
```
|
||||
|
||||
### Loading specific components
|
||||
|
||||
```python
|
||||
from diffusers import UNet2DConditionModel, AutoencoderKL
|
||||
|
||||
# Load custom VAE
|
||||
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse")
|
||||
|
||||
# Use with pipeline
|
||||
pipe = DiffusionPipeline.from_pretrained(
|
||||
"stable-diffusion-v1-5/stable-diffusion-v1-5",
|
||||
vae=vae,
|
||||
torch_dtype=torch.float16
|
||||
)
|
||||
```
|
||||
|
||||
## Batch generation
|
||||
|
||||
Generate multiple images efficiently:
|
||||
|
||||
```python
|
||||
# Multiple prompts
|
||||
prompts = [
|
||||
"A cat playing piano",
|
||||
"A dog reading a book",
|
||||
"A bird painting a picture"
|
||||
]
|
||||
|
||||
images = pipe(prompts, num_inference_steps=30).images
|
||||
|
||||
# Multiple images per prompt
|
||||
images = pipe(
|
||||
"A beautiful sunset",
|
||||
num_images_per_prompt=4,
|
||||
num_inference_steps=30
|
||||
).images
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: High-quality generation
|
||||
|
||||
```python
|
||||
from diffusers import StableDiffusionXLPipeline, DPMSolverMultistepScheduler
|
||||
import torch
|
||||
|
||||
# 1. Load SDXL with optimizations
|
||||
pipe = StableDiffusionXLPipeline.from_pretrained(
|
||||
"stabilityai/stable-diffusion-xl-base-1.0",
|
||||
torch_dtype=torch.float16,
|
||||
variant="fp16"
|
||||
)
|
||||
pipe.to("cuda")
|
||||
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
|
||||
pipe.enable_model_cpu_offload()
|
||||
|
||||
# 2. Generate with quality settings
|
||||
image = pipe(
|
||||
prompt="A majestic lion in the savanna, golden hour lighting, 8k, detailed fur",
|
||||
negative_prompt="blurry, low quality, cartoon, anime, sketch",
|
||||
num_inference_steps=30,
|
||||
guidance_scale=7.5,
|
||||
height=1024,
|
||||
width=1024
|
||||
).images[0]
|
||||
```
|
||||
|
||||
### Workflow 2: Fast prototyping
|
||||
|
||||
```python
|
||||
from diffusers import AutoPipelineForText2Image, LCMScheduler
|
||||
import torch
|
||||
|
||||
# Use LCM for 4-8 step generation
|
||||
pipe = AutoPipelineForText2Image.from_pretrained(
|
||||
"stabilityai/stable-diffusion-xl-base-1.0",
|
||||
torch_dtype=torch.float16
|
||||
).to("cuda")
|
||||
|
||||
# Load LCM LoRA for fast generation
|
||||
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")
|
||||
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
||||
pipe.fuse_lora()
|
||||
|
||||
# Generate in ~1 second
|
||||
image = pipe(
|
||||
"A beautiful landscape",
|
||||
num_inference_steps=4,
|
||||
guidance_scale=1.0
|
||||
).images[0]
|
||||
```
|
||||
|
||||
## Common issues
|
||||
|
||||
**CUDA out of memory:**
|
||||
```python
|
||||
# Enable memory optimizations
|
||||
pipe.enable_model_cpu_offload()
|
||||
pipe.enable_attention_slicing()
|
||||
pipe.enable_vae_slicing()
|
||||
|
||||
# Or use lower precision
|
||||
pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16)
|
||||
```
|
||||
|
||||
**Black/noise images:**
|
||||
```python
|
||||
# Check VAE configuration
|
||||
# Use safety checker bypass if needed
|
||||
pipe.safety_checker = None
|
||||
|
||||
# Ensure proper dtype consistency
|
||||
pipe = pipe.to(dtype=torch.float16)
|
||||
```
|
||||
|
||||
**Slow generation:**
|
||||
```python
|
||||
# Use faster scheduler
|
||||
from diffusers import DPMSolverMultistepScheduler
|
||||
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
|
||||
|
||||
# Reduce steps
|
||||
image = pipe(prompt, num_inference_steps=20).images[0]
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- **[Advanced Usage](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\stable-diffusion/references/advanced-usage.md)** - Custom pipelines, fine-tuning, deployment
|
||||
- **[Troubleshooting](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\stable-diffusion/references/troubleshooting.md)** - Common issues and solutions
|
||||
|
||||
## Resources
|
||||
|
||||
- **Documentation**: https://huggingface.co/docs/diffusers
|
||||
- **Repository**: https://github.com/huggingface/diffusers
|
||||
- **Model Hub**: https://huggingface.co/models?library=diffusers
|
||||
- **Discord**: https://discord.gg/diffusers
|
||||
@@ -0,0 +1,208 @@
|
||||
---
|
||||
title: "Tensorrt Llm — High-throughput LLM inference on NVIDIA GPUs"
|
||||
sidebar_label: "Tensorrt Llm"
|
||||
description: "High-throughput LLM inference on NVIDIA GPUs"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Tensorrt Llm
|
||||
|
||||
High-throughput LLM inference on NVIDIA GPUs.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/tensorrt-llm` |
|
||||
| Path | `optional-skills/mlops\tensorrt-llm` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `tensorrt-llm`, `torch` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Inference Serving`, `TensorRT-LLM`, `NVIDIA`, `Inference Optimization`, `High Throughput`, `Low Latency`, `Production`, `FP8`, `INT4`, `In-Flight Batching`, `Multi-GPU` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# TensorRT-LLM
|
||||
|
||||
NVIDIA's open-source library for optimizing LLM inference with high performance on NVIDIA GPUs.
|
||||
|
||||
## When to use TensorRT-LLM
|
||||
|
||||
**Use TensorRT-LLM when:**
|
||||
- Deploying on NVIDIA GPUs (A100, H100, GB200)
|
||||
- Need maximum throughput (24,000+ tokens/sec on Llama 3)
|
||||
- Require low latency for real-time applications
|
||||
- Working with quantized models (FP8, INT4, FP4)
|
||||
- Scaling across multiple GPUs or nodes
|
||||
|
||||
**Use vLLM instead when:**
|
||||
- Need simpler setup and Python-first API
|
||||
- Want PagedAttention without TensorRT compilation
|
||||
- Working with AMD GPUs or non-NVIDIA hardware
|
||||
|
||||
**Use llama.cpp instead when:**
|
||||
- Deploying on CPU or Apple Silicon
|
||||
- Need edge deployment without NVIDIA GPUs
|
||||
- Want simpler GGUF quantization format
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Docker (recommended) — images are on NGC (nvcr.io), not Docker Hub.
|
||||
# Replace x.y.z with the desired version (e.g. 1.2.1). Browse tags on NGC:
|
||||
# https://catalog.ngc.nvidia.com/orgs/nvidia/teams/tensorrt-llm/containers/release/tags
|
||||
docker pull nvcr.io/nvidia/tensorrt-llm/release:x.y.z
|
||||
|
||||
# pip install (current stable GA)
|
||||
pip install tensorrt_llm
|
||||
|
||||
# Requires CUDA 13.2.1, TensorRT 10.x, Python 3.10-3.12
|
||||
```
|
||||
|
||||
### Basic inference
|
||||
|
||||
```python
|
||||
from tensorrt_llm import LLM, SamplingParams
|
||||
|
||||
# Initialize model
|
||||
llm = LLM(model="meta-llama/Meta-Llama-3-8B")
|
||||
|
||||
# Configure sampling
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=100,
|
||||
temperature=0.7,
|
||||
top_p=0.9
|
||||
)
|
||||
|
||||
# Generate
|
||||
prompts = ["Explain quantum computing"]
|
||||
outputs = llm.generate(prompts, sampling_params)
|
||||
|
||||
for output in outputs:
|
||||
print(output.text)
|
||||
```
|
||||
|
||||
### Serving with trtllm-serve
|
||||
|
||||
```bash
|
||||
# Start server (automatic model download and compilation)
|
||||
trtllm-serve meta-llama/Meta-Llama-3-8B \
|
||||
--tp_size 4 \ # Tensor parallelism (4 GPUs)
|
||||
--max_batch_size 256 \
|
||||
--max_num_tokens 4096
|
||||
|
||||
# Client request
|
||||
curl -X POST http://localhost:8000/v1/chat/completions \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "meta-llama/Meta-Llama-3-8B",
|
||||
"messages": [{"role": "user", "content": "Hello!"}],
|
||||
"temperature": 0.7,
|
||||
"max_tokens": 100
|
||||
}'
|
||||
```
|
||||
|
||||
## Key features
|
||||
|
||||
### Performance optimizations
|
||||
- **In-flight batching**: Dynamic batching during generation
|
||||
- **Paged KV cache**: Efficient memory management
|
||||
- **Flash Attention**: Optimized attention kernels
|
||||
- **Quantization**: FP8, INT4, FP4 for 2-4× faster inference
|
||||
- **CUDA graphs**: Reduced kernel launch overhead
|
||||
|
||||
### Parallelism
|
||||
- **Tensor parallelism (TP)**: Split model across GPUs
|
||||
- **Pipeline parallelism (PP)**: Layer-wise distribution
|
||||
- **Expert parallelism**: For Mixture-of-Experts models
|
||||
- **Multi-node**: Scale beyond single machine
|
||||
|
||||
### Advanced features
|
||||
- **Speculative decoding**: Faster generation with draft models
|
||||
- **LoRA serving**: Efficient multi-adapter deployment
|
||||
- **Disaggregated serving**: Separate prefill and generation
|
||||
|
||||
## Common patterns
|
||||
|
||||
### Quantized model (FP8)
|
||||
|
||||
```python
|
||||
from tensorrt_llm import LLM
|
||||
|
||||
# Load FP8 quantized model (2× faster, 50% memory)
|
||||
llm = LLM(
|
||||
model="meta-llama/Meta-Llama-3-70B",
|
||||
dtype="fp8",
|
||||
max_num_tokens=8192
|
||||
)
|
||||
|
||||
# Inference same as before
|
||||
outputs = llm.generate(["Summarize this article..."])
|
||||
```
|
||||
|
||||
### Multi-GPU deployment
|
||||
|
||||
```python
|
||||
# Tensor parallelism across 8 GPUs
|
||||
llm = LLM(
|
||||
model="meta-llama/Meta-Llama-3-405B",
|
||||
tensor_parallel_size=8,
|
||||
dtype="fp8"
|
||||
)
|
||||
```
|
||||
|
||||
### Batch inference
|
||||
|
||||
```python
|
||||
# Process 100 prompts efficiently
|
||||
prompts = [f"Question {i}: ..." for i in range(100)]
|
||||
|
||||
outputs = llm.generate(
|
||||
prompts,
|
||||
sampling_params=SamplingParams(max_tokens=200)
|
||||
)
|
||||
|
||||
# Automatic in-flight batching for maximum throughput
|
||||
```
|
||||
|
||||
## Performance benchmarks
|
||||
|
||||
**Meta Llama 3-8B** (H100 GPU):
|
||||
- Throughput: 24,000 tokens/sec
|
||||
- Latency: ~10ms per token
|
||||
- vs PyTorch: **100× faster**
|
||||
|
||||
**Llama 3-70B** (8× A100 80GB):
|
||||
- FP8 quantization: 2× faster than FP16
|
||||
- Memory: 50% reduction with FP8
|
||||
|
||||
## Supported models
|
||||
|
||||
- **LLaMA family**: Llama 2, Llama 3, CodeLlama
|
||||
- **GPT family**: GPT-2, GPT-J, GPT-NeoX
|
||||
- **Qwen**: Qwen, Qwen2, QwQ
|
||||
- **DeepSeek**: DeepSeek-V2, DeepSeek-V3
|
||||
- **Mixtral**: Mixtral-8x7B, Mixtral-8x22B
|
||||
- **Vision**: LLaVA, Phi-3-vision
|
||||
- **100+ models** on HuggingFace
|
||||
|
||||
## References
|
||||
|
||||
- **[Optimization Guide](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\tensorrt-llm/references/optimization.md)** - Quantization, batching, KV cache tuning
|
||||
- **[Multi-GPU Setup](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\tensorrt-llm/references/multi-gpu.md)** - Tensor/pipeline parallelism, multi-node
|
||||
- **[Serving Guide](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\tensorrt-llm/references/serving.md)** - Production deployment, monitoring, autoscaling
|
||||
|
||||
## Resources
|
||||
|
||||
- **Docs**: https://nvidia.github.io/TensorRT-LLM/
|
||||
- **GitHub**: https://github.com/NVIDIA/TensorRT-LLM
|
||||
- **Models**: https://huggingface.co/models?library=tensorrt_llm
|
||||
@@ -0,0 +1,404 @@
|
||||
---
|
||||
title: "Torchtitan — Pretrain LLMs at scale with PyTorch 4D parallelism"
|
||||
sidebar_label: "Torchtitan"
|
||||
description: "Pretrain LLMs at scale with PyTorch 4D parallelism"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Torchtitan
|
||||
|
||||
Pretrain LLMs at scale with PyTorch 4D parallelism.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/torchtitan` |
|
||||
| Path | `optional-skills/mlops\torchtitan` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `torch>=2.6.0`, `torchtitan>=0.2.0`, `torchao>=0.5.0` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Model Architecture`, `Distributed Training`, `TorchTitan`, `FSDP2`, `Tensor Parallel`, `Pipeline Parallel`, `Context Parallel`, `Float8`, `Llama`, `Pretraining` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# TorchTitan - PyTorch Native Distributed LLM Pretraining
|
||||
|
||||
## Quick start
|
||||
|
||||
TorchTitan is PyTorch's official platform for large-scale LLM pretraining with composable 4D parallelism (FSDP2, TP, PP, CP), achieving 65%+ speedups over baselines on H100 GPUs.
|
||||
|
||||
**Installation**:
|
||||
```bash
|
||||
# From PyPI (stable)
|
||||
pip install torchtitan
|
||||
|
||||
# From source (latest features, requires PyTorch nightly)
|
||||
git clone https://github.com/pytorch/torchtitan
|
||||
cd torchtitan
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
**Download tokenizer**:
|
||||
```bash
|
||||
# Get HF token from https://huggingface.co/settings/tokens
|
||||
python scripts/download_hf_assets.py --repo_id meta-llama/Llama-3.1-8B --assets tokenizer --hf_token=...
|
||||
```
|
||||
|
||||
**Start training on 8 GPUs**:
|
||||
```bash
|
||||
# Configs are selected by name from the Python config registry
|
||||
# (torchtitan/models/llama3/config_registry.py), not by TOML path
|
||||
MODULE=llama3 CONFIG=llama3_8b ./run_train.sh
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: Pretrain Llama 3.1 8B on single node
|
||||
|
||||
Copy this checklist:
|
||||
|
||||
```
|
||||
Single Node Pretraining:
|
||||
- [ ] Step 1: Download tokenizer
|
||||
- [ ] Step 2: Configure training
|
||||
- [ ] Step 3: Launch training
|
||||
- [ ] Step 4: Monitor and checkpoint
|
||||
```
|
||||
|
||||
**Step 1: Download tokenizer**
|
||||
|
||||
```bash
|
||||
python scripts/download_hf_assets.py \
|
||||
--repo_id meta-llama/Llama-3.1-8B \
|
||||
--assets tokenizer \
|
||||
--hf_token=YOUR_HF_TOKEN
|
||||
```
|
||||
|
||||
**Step 2: Configure training**
|
||||
|
||||
In torchtitan's current layout, run configs are defined in a Python **config registry**
|
||||
(`torchtitan/models/llama3/config_registry.py`) and selected by name via `CONFIG=<name>`
|
||||
(or `--config <name>`). To customize, register your own config in the registry, or override
|
||||
individual fields on the command line (e.g. `--optimizer.lr 3e-4 --training.steps 1000`).
|
||||
|
||||
The equivalent settings for an 8B run look like this (shown as fields; set them in the
|
||||
registry entry or as `--section.key value` overrides):
|
||||
|
||||
```toml
|
||||
# fields for a llama3 8B run (register in config_registry.py or pass as --overrides)
|
||||
[job]
|
||||
dump_folder = "./outputs"
|
||||
description = "Llama 3.1 8B training"
|
||||
|
||||
[model]
|
||||
name = "llama3"
|
||||
flavor = "8B"
|
||||
hf_assets_path = "./assets/hf/Llama-3.1-8B"
|
||||
|
||||
[optimizer]
|
||||
name = "AdamW"
|
||||
lr = 3e-4
|
||||
|
||||
[lr_scheduler]
|
||||
warmup_steps = 200
|
||||
|
||||
[training]
|
||||
local_batch_size = 2
|
||||
seq_len = 8192
|
||||
max_norm = 1.0
|
||||
steps = 1000
|
||||
dataset = "c4"
|
||||
|
||||
[parallelism]
|
||||
data_parallel_shard_degree = -1 # Use all GPUs for FSDP
|
||||
|
||||
[activation_checkpoint]
|
||||
mode = "selective"
|
||||
selective_ac_option = "op"
|
||||
|
||||
[checkpoint]
|
||||
enable = true
|
||||
folder = "checkpoint"
|
||||
interval = 500
|
||||
```
|
||||
|
||||
**Step 3: Launch training**
|
||||
|
||||
```bash
|
||||
# 8 GPUs on single node (config selected by name from the registry)
|
||||
MODULE=llama3 CONFIG=llama3_8b ./run_train.sh
|
||||
|
||||
# Override individual fields on the command line
|
||||
MODULE=llama3 CONFIG=llama3_8b ./run_train.sh --optimizer.lr 3e-4 --training.steps 1000
|
||||
|
||||
# Or explicitly with torchrun (run_train.sh wraps this)
|
||||
torchrun --nproc_per_node=8 \
|
||||
-m torchtitan.train \
|
||||
--module llama3 --config llama3_8b
|
||||
```
|
||||
|
||||
**Step 4: Monitor and checkpoint**
|
||||
|
||||
TensorBoard logs are saved to `./outputs/tb/`:
|
||||
```bash
|
||||
tensorboard --logdir ./outputs/tb
|
||||
```
|
||||
|
||||
### Workflow 2: Multi-node training with SLURM
|
||||
|
||||
```
|
||||
Multi-Node Training:
|
||||
- [ ] Step 1: Configure parallelism for scale
|
||||
- [ ] Step 2: Set up SLURM script
|
||||
- [ ] Step 3: Submit job
|
||||
- [ ] Step 4: Resume from checkpoint
|
||||
```
|
||||
|
||||
**Step 1: Configure parallelism for scale**
|
||||
|
||||
For 70B model on 256 GPUs (32 nodes):
|
||||
```toml
|
||||
[parallelism]
|
||||
data_parallel_shard_degree = 32 # FSDP across 32 ranks
|
||||
tensor_parallel_degree = 8 # TP within node
|
||||
pipeline_parallel_degree = 1 # No PP for 70B
|
||||
context_parallel_degree = 1 # Increase for long sequences
|
||||
```
|
||||
|
||||
**Step 2: Set up SLURM script**
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
#SBATCH --job-name=llama70b
|
||||
#SBATCH --nodes=32
|
||||
#SBATCH --ntasks-per-node=8
|
||||
#SBATCH --gpus-per-node=8
|
||||
|
||||
srun torchrun \
|
||||
--nnodes=32 \
|
||||
--nproc_per_node=8 \
|
||||
--rdzv_backend=c10d \
|
||||
--rdzv_endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
-m torchtitan.train \
|
||||
--module llama3 --config llama3_70b
|
||||
```
|
||||
|
||||
**Step 3: Submit job**
|
||||
|
||||
```bash
|
||||
sbatch multinode_trainer.slurm
|
||||
```
|
||||
|
||||
**Step 4: Resume from checkpoint**
|
||||
|
||||
Training auto-resumes if checkpoint exists in configured folder.
|
||||
|
||||
### Workflow 3: Enable Float8 training for H100s
|
||||
|
||||
Float8 provides 30-50% speedup on H100 GPUs.
|
||||
|
||||
```
|
||||
Float8 Training:
|
||||
- [ ] Step 1: Install torchao
|
||||
- [ ] Step 2: Configure Float8
|
||||
- [ ] Step 3: Launch with compile
|
||||
```
|
||||
|
||||
**Step 1: Install torchao**
|
||||
|
||||
```bash
|
||||
USE_CPP=0 pip install git+https://github.com/pytorch/ao.git
|
||||
```
|
||||
|
||||
**Step 2: Configure Float8**
|
||||
|
||||
In the current torchtitan, Float8 is applied at config time via the `quantization`
|
||||
parameter in your `model_registry()` call inside the config registry (not via a
|
||||
`[quantize.linear.float8]` TOML section). Add a `Float8LinearConverter.Config`:
|
||||
|
||||
```python
|
||||
# in torchtitan/models/llama3/config_registry.py (your model_registry(...) call)
|
||||
from torchtitan.components.quantization import Float8LinearConverter
|
||||
|
||||
model_spec = model_registry(
|
||||
"8B",
|
||||
quantization=[
|
||||
Float8LinearConverter.Config(
|
||||
recipe_name="rowwise", # or "rowwise_with_gw_hp"
|
||||
filter_fqns=["output"], # skip layers too small to benefit
|
||||
model_compile_enabled=True, # requires torch.compile for competitive perf
|
||||
),
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
Enable `torch.compile` in your run config too:
|
||||
```toml
|
||||
[compile]
|
||||
enable = true
|
||||
components = ["model", "loss"]
|
||||
```
|
||||
|
||||
**Step 3: Launch with compile**
|
||||
|
||||
```bash
|
||||
# Float8 config is baked into the registered config; just select it and enable compile
|
||||
MODULE=llama3 CONFIG=llama3_8b ./run_train.sh --compile.enable
|
||||
```
|
||||
|
||||
### Workflow 4: 4D parallelism for 405B models
|
||||
|
||||
```
|
||||
4D Parallelism (FSDP + TP + PP + CP):
|
||||
- [ ] Step 1: Create seed checkpoint
|
||||
- [ ] Step 2: Configure 4D parallelism
|
||||
- [ ] Step 3: Launch on 512 GPUs
|
||||
```
|
||||
|
||||
**Step 1: Create seed checkpoint**
|
||||
|
||||
Required for consistent initialization across PP stages:
|
||||
```bash
|
||||
NGPU=1 MODULE=llama3 CONFIG=llama3_405b ./run_train.sh \
|
||||
--checkpoint.enable \
|
||||
--checkpoint.create_seed_checkpoint \
|
||||
--parallelism.data_parallel_shard_degree 1 \
|
||||
--parallelism.tensor_parallel_degree 1 \
|
||||
--parallelism.pipeline_parallel_degree 1
|
||||
```
|
||||
|
||||
**Step 2: Configure 4D parallelism**
|
||||
|
||||
```toml
|
||||
[parallelism]
|
||||
data_parallel_shard_degree = 8 # FSDP
|
||||
tensor_parallel_degree = 8 # TP within node
|
||||
pipeline_parallel_degree = 8 # PP across nodes
|
||||
context_parallel_degree = 1 # CP for long sequences
|
||||
|
||||
[training]
|
||||
local_batch_size = 32
|
||||
seq_len = 8192
|
||||
```
|
||||
|
||||
**Step 3: Launch on 512 GPUs**
|
||||
|
||||
```bash
|
||||
# 64 nodes x 8 GPUs = 512 GPUs
|
||||
srun torchrun --nnodes=64 --nproc_per_node=8 \
|
||||
-m torchtitan.train \
|
||||
--module llama3 --config llama3_405b
|
||||
```
|
||||
|
||||
## When to use vs alternatives
|
||||
|
||||
**Use TorchTitan when:**
|
||||
- Pretraining LLMs from scratch (8B to 405B+)
|
||||
- Need PyTorch-native solution without third-party dependencies
|
||||
- Require composable 4D parallelism (FSDP2, TP, PP, CP)
|
||||
- Training on H100s with Float8 support
|
||||
- Want interoperable checkpoints with torchtune/HuggingFace
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **Megatron-LM**: Maximum performance for NVIDIA-only deployments
|
||||
- **DeepSpeed**: Broader ZeRO optimization ecosystem, inference support
|
||||
- **Axolotl/TRL**: Fine-tuning rather than pretraining
|
||||
- **LitGPT**: Educational, smaller-scale training
|
||||
|
||||
## Common issues
|
||||
|
||||
**Issue: Out of memory on large models**
|
||||
|
||||
Enable activation checkpointing and reduce batch size:
|
||||
```toml
|
||||
[activation_checkpoint]
|
||||
mode = "full" # Instead of "selective"
|
||||
|
||||
[training]
|
||||
local_batch_size = 1
|
||||
```
|
||||
|
||||
Or use gradient accumulation:
|
||||
```toml
|
||||
[training]
|
||||
local_batch_size = 1
|
||||
global_batch_size = 32 # Accumulates gradients
|
||||
```
|
||||
|
||||
**Issue: TP causes high memory with async collectives**
|
||||
|
||||
Set environment variable:
|
||||
```bash
|
||||
export TORCH_NCCL_AVOID_RECORD_STREAMS=1
|
||||
```
|
||||
|
||||
**Issue: Float8 training not faster**
|
||||
|
||||
Float8 only benefits large GEMMs. Filter small layers via the converter's `filter_fqns`:
|
||||
```python
|
||||
from torchtitan.components.quantization import Float8LinearConverter
|
||||
|
||||
Float8LinearConverter.Config(
|
||||
# add "auto_filter_small_kn" to auto-skip layers too small to benefit
|
||||
filter_fqns=["attention.wk", "attention.wv", "output", "auto_filter_small_kn"],
|
||||
model_compile_enabled=True,
|
||||
)
|
||||
```
|
||||
|
||||
**Issue: Checkpoint loading fails after parallelism change**
|
||||
|
||||
Use DCP's resharding capability:
|
||||
```bash
|
||||
# Convert sharded checkpoint to single file
|
||||
python -m torch.distributed.checkpoint.format_utils \
|
||||
dcp_to_torch checkpoint/step-1000 checkpoint.pt
|
||||
```
|
||||
|
||||
**Issue: Pipeline parallelism initialization**
|
||||
|
||||
Create seed checkpoint first (see Workflow 4, Step 1).
|
||||
|
||||
## Supported models
|
||||
|
||||
| Model | Sizes | Status |
|
||||
|-------|-------|--------|
|
||||
| Llama 3.1 | 8B, 70B, 405B | Production |
|
||||
| Llama 4 | Various | Experimental |
|
||||
| DeepSeek V3 | 16B, 236B, 671B (MoE) | Experimental |
|
||||
| GPT-OSS | 20B, 120B (MoE) | Experimental |
|
||||
| Qwen 3 | Various | Experimental |
|
||||
| Flux | Diffusion | Experimental |
|
||||
|
||||
## Performance benchmarks (H100)
|
||||
|
||||
| Model | GPUs | Parallelism | TPS/GPU | Techniques |
|
||||
|-------|------|-------------|---------|------------|
|
||||
| Llama 8B | 8 | FSDP | 5,762 | Baseline |
|
||||
| Llama 8B | 8 | FSDP+compile+FP8 | 8,532 | +48% |
|
||||
| Llama 70B | 256 | FSDP+TP+AsyncTP | 876 | 2D parallel |
|
||||
| Llama 405B | 512 | FSDP+TP+PP | 128 | 3D parallel |
|
||||
|
||||
## Advanced topics
|
||||
|
||||
**FSDP2 configuration**: See [references/fsdp.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\torchtitan/references/fsdp.md) for detailed FSDP2 vs FSDP1 comparison and ZeRO equivalents.
|
||||
|
||||
**Float8 training**: See [references/float8.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\torchtitan/references/float8.md) for tensorwise vs rowwise scaling recipes.
|
||||
|
||||
**Checkpointing**: See [references/checkpoint.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\torchtitan/references/checkpoint.md) for HuggingFace conversion and async checkpointing.
|
||||
|
||||
**Adding custom models**: See [references/custom-models.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\torchtitan/references/custom-models.md) for TrainSpec protocol.
|
||||
|
||||
## Resources
|
||||
|
||||
- GitHub: https://github.com/pytorch/torchtitan
|
||||
- Paper: https://arxiv.org/abs/2410.06511
|
||||
- ICLR 2025: https://iclr.cc/virtual/2025/poster/29620
|
||||
- PyTorch Forum: https://discuss.pytorch.org/c/distributed/torchtitan/44
|
||||
@@ -0,0 +1,181 @@
|
||||
---
|
||||
title: "Axolotl — Axolotl: YAML LLM fine-tuning (LoRA, DPO, GRPO)"
|
||||
sidebar_label: "Axolotl"
|
||||
description: "Axolotl: YAML LLM fine-tuning (LoRA, DPO, GRPO)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Axolotl
|
||||
|
||||
Axolotl: YAML LLM fine-tuning (LoRA, DPO, GRPO).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/axolotl` |
|
||||
| Path | `optional-skills/mlops\training\axolotl` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `axolotl`, `torch`, `transformers`, `datasets`, `peft`, `accelerate`, `deepspeed` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Fine-Tuning`, `Axolotl`, `LLM`, `LoRA`, `QLoRA`, `DPO`, `KTO`, `ORPO`, `GRPO`, `YAML`, `HuggingFace`, `DeepSpeed`, `Multimodal` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Axolotl Skill
|
||||
|
||||
## What's inside
|
||||
|
||||
Expert guidance for fine-tuning LLMs with Axolotl — YAML configs, 100+ models, LoRA/QLoRA, DPO/KTO/ORPO/GRPO, multimodal support.
|
||||
|
||||
Assistance with axolotl development, generated from official documentation.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
This skill should be triggered when:
|
||||
- Working with axolotl
|
||||
- Asking about axolotl features or APIs
|
||||
- Implementing axolotl solutions
|
||||
- Debugging axolotl code
|
||||
- Learning axolotl best practices
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Common Patterns
|
||||
|
||||
**Pattern 1:** To validate that acceptable data transfer speeds exist for your training job, running NCCL Tests can help pinpoint bottlenecks, for example:
|
||||
|
||||
```
|
||||
./build/all_reduce_perf -b 8 -e 128M -f 2 -g 3
|
||||
```
|
||||
|
||||
**Pattern 2:** Configure your model to use FSDP in the Axolotl yaml. For example:
|
||||
|
||||
```
|
||||
fsdp_version: 2
|
||||
fsdp_config:
|
||||
offload_params: true
|
||||
state_dict_type: FULL_STATE_DICT
|
||||
auto_wrap_policy: TRANSFORMER_BASED_WRAP
|
||||
transformer_layer_cls_to_wrap: LlamaDecoderLayer
|
||||
reshard_after_forward: true
|
||||
```
|
||||
|
||||
**Pattern 3:** The context_parallel_size should be a divisor of the total number of GPUs. For example:
|
||||
|
||||
```
|
||||
context_parallel_size
|
||||
```
|
||||
|
||||
**Pattern 4:** For example: - With 8 GPUs and no sequence parallelism: 8 different batches processed per step - With 8 GPUs and context_parallel_size=4: Only 2 different batches processed per step (each split across 4 GPUs) - If your per-GPU micro_batch_size is 2, the global batch size decreases from 16 to 4
|
||||
|
||||
```
|
||||
context_parallel_size=4
|
||||
```
|
||||
|
||||
**Pattern 5:** Setting save_compressed: true in your configuration enables saving models in a compressed format, which: - Reduces disk space usage by approximately 40% - Maintains compatibility with vLLM for accelerated inference - Maintains compatibility with llmcompressor for further optimization (example: quantization)
|
||||
|
||||
```
|
||||
save_compressed: true
|
||||
```
|
||||
|
||||
**Pattern 6:** Note It is not necessary to place your integration in the integrations folder. It can be in any location, so long as it’s installed in a package in your python env. See this repo for an example: https://github.com/axolotl-ai-cloud/diff-transformer
|
||||
|
||||
```
|
||||
integrations
|
||||
```
|
||||
|
||||
**Pattern 7:** Handle both single-example and batched data. - single example: sample[‘input_ids’] is a list[int] - batched data: sample[‘input_ids’] is a list[list[int]]
|
||||
|
||||
```
|
||||
utils.trainer.drop_long_seq(sample, sequence_len=2048, min_sequence_len=2)
|
||||
```
|
||||
|
||||
### Example Code Patterns
|
||||
|
||||
**Example 1** (python):
|
||||
```python
|
||||
cli.cloud.modal_.ModalCloud(config, app=None)
|
||||
```
|
||||
|
||||
**Example 2** (python):
|
||||
```python
|
||||
cli.cloud.modal_.run_cmd(cmd, run_folder, volumes=None)
|
||||
```
|
||||
|
||||
**Example 3** (python):
|
||||
```python
|
||||
core.trainers.base.AxolotlTrainer(
|
||||
*_args,
|
||||
bench_data_collator=None,
|
||||
eval_data_collator=None,
|
||||
dataset_tags=None,
|
||||
**kwargs,
|
||||
)
|
||||
```
|
||||
|
||||
**Example 4** (python):
|
||||
```python
|
||||
core.trainers.base.AxolotlTrainer.log(logs, start_time=None)
|
||||
```
|
||||
|
||||
**Example 5** (python):
|
||||
```python
|
||||
prompt_strategies.input_output.RawInputOutputPrompter()
|
||||
```
|
||||
|
||||
## Reference Files
|
||||
|
||||
This skill includes comprehensive documentation in `references/`:
|
||||
|
||||
- **api.md** - Api documentation
|
||||
- **dataset-formats.md** - Dataset-Formats documentation
|
||||
- **other.md** - Other documentation
|
||||
|
||||
Use `view` to read specific reference files when detailed information is needed.
|
||||
|
||||
## Working with This Skill
|
||||
|
||||
### For Beginners
|
||||
Start with the getting_started or tutorials reference files for foundational concepts.
|
||||
|
||||
### For Specific Features
|
||||
Use the appropriate category reference file (api, guides, etc.) for detailed information.
|
||||
|
||||
### For Code Examples
|
||||
The quick reference section above contains common patterns extracted from the official docs.
|
||||
|
||||
## Resources
|
||||
|
||||
### references/
|
||||
Organized documentation extracted from official sources. These files contain:
|
||||
- Detailed explanations
|
||||
- Code examples with language annotations
|
||||
- Links to original documentation
|
||||
- Table of contents for quick navigation
|
||||
|
||||
### scripts/
|
||||
Add helper scripts here for common automation tasks.
|
||||
|
||||
### assets/
|
||||
Add templates, boilerplate, or example projects here.
|
||||
|
||||
## Notes
|
||||
|
||||
- This skill was automatically generated from official documentation
|
||||
- Reference files preserve the structure and examples from source docs
|
||||
- Code examples include language detection for better syntax highlighting
|
||||
- Quick reference patterns are extracted from common usage examples in the docs
|
||||
|
||||
## Updating
|
||||
|
||||
To refresh this skill with updated documentation:
|
||||
1. Re-run the scraper with the same configuration
|
||||
2. The skill will be rebuilt with the latest information
|
||||
@@ -0,0 +1,512 @@
|
||||
---
|
||||
title: "Trl Fine Tuning — TRL: SFT, DPO, GRPO, RLOO reward modeling for LLM RLHF"
|
||||
sidebar_label: "Trl Fine Tuning"
|
||||
description: "TRL: SFT, DPO, GRPO, RLOO reward modeling for LLM RLHF"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Trl Fine Tuning
|
||||
|
||||
TRL: SFT, DPO, GRPO, RLOO reward modeling for LLM RLHF.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/trl-fine-tuning` |
|
||||
| Path | `optional-skills/mlops\training\trl-fine-tuning` |
|
||||
| Version | `1.0.1` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `trl`, `transformers`, `datasets`, `peft`, `accelerate`, `torch` |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Post-Training`, `TRL`, `Reinforcement Learning`, `Fine-Tuning`, `SFT`, `DPO`, `GRPO`, `RLOO`, `RLHF`, `Preference Alignment`, `HuggingFace` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# TRL - Transformer Reinforcement Learning
|
||||
|
||||
## Quick start
|
||||
|
||||
TRL provides post-training methods for aligning language models with human preferences.
|
||||
|
||||
**Installation**:
|
||||
```bash
|
||||
pip install trl transformers datasets peft accelerate
|
||||
```
|
||||
|
||||
**Supervised Fine-Tuning** (instruction tuning):
|
||||
```python
|
||||
from trl import SFTTrainer
|
||||
|
||||
trainer = SFTTrainer(
|
||||
model="Qwen/Qwen2.5-0.5B",
|
||||
train_dataset=dataset, # Prompt-completion pairs
|
||||
)
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
**DPO** (align with preferences):
|
||||
```python
|
||||
from trl import DPOTrainer, DPOConfig
|
||||
|
||||
config = DPOConfig(output_dir="model-dpo", beta=0.1)
|
||||
trainer = DPOTrainer(
|
||||
model=model,
|
||||
args=config,
|
||||
train_dataset=preference_dataset, # chosen/rejected pairs
|
||||
processing_class=tokenizer
|
||||
)
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
## Common workflows
|
||||
|
||||
### Workflow 1: Full RLHF pipeline (SFT → Reward Model → RLOO)
|
||||
|
||||
Complete pipeline from base model to human-aligned model.
|
||||
|
||||
> **Note (TRL 1.x):** PPO has been **removed** from TRL — `PPOTrainer`, `PPOConfig`, and
|
||||
> `python -m trl.scripts.ppo` no longer exist. Use an online-RL trainer TRL still ships:
|
||||
> **RLOO** (`RLOOTrainer` / `trl rloo`) is the closest drop-in for a reward-model-driven
|
||||
> RLHF pipeline, and **GRPO** (`GRPOTrainer` / `trl grpo`, see Workflow 3) is the
|
||||
> memory-efficient alternative. The step below uses RLOO.
|
||||
|
||||
Copy this checklist:
|
||||
|
||||
```
|
||||
RLHF Training:
|
||||
- [ ] Step 1: Supervised fine-tuning (SFT)
|
||||
- [ ] Step 2: Train reward model
|
||||
- [ ] Step 3: RLOO reinforcement learning
|
||||
- [ ] Step 4: Evaluate aligned model
|
||||
```
|
||||
|
||||
**Step 1: Supervised fine-tuning**
|
||||
|
||||
Train base model on instruction-following data:
|
||||
|
||||
```python
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
from trl import SFTTrainer, SFTConfig
|
||||
from datasets import load_dataset
|
||||
|
||||
# Load model
|
||||
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B")
|
||||
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
|
||||
|
||||
# Load instruction dataset
|
||||
dataset = load_dataset("trl-lib/Capybara", split="train")
|
||||
|
||||
# Configure training
|
||||
training_args = SFTConfig(
|
||||
output_dir="Qwen2.5-0.5B-SFT",
|
||||
per_device_train_batch_size=4,
|
||||
num_train_epochs=1,
|
||||
learning_rate=2e-5,
|
||||
logging_steps=10,
|
||||
save_strategy="epoch"
|
||||
)
|
||||
|
||||
# Train
|
||||
trainer = SFTTrainer(
|
||||
model=model,
|
||||
args=training_args,
|
||||
train_dataset=dataset,
|
||||
processing_class=tokenizer
|
||||
)
|
||||
trainer.train()
|
||||
trainer.save_model()
|
||||
```
|
||||
|
||||
**Step 2: Train reward model**
|
||||
|
||||
Train model to predict human preferences:
|
||||
|
||||
```python
|
||||
from transformers import AutoModelForSequenceClassification
|
||||
from trl import RewardTrainer, RewardConfig
|
||||
|
||||
# Load SFT model as base
|
||||
model = AutoModelForSequenceClassification.from_pretrained(
|
||||
"Qwen2.5-0.5B-SFT",
|
||||
num_labels=1 # Single reward score
|
||||
)
|
||||
tokenizer = AutoTokenizer.from_pretrained("Qwen2.5-0.5B-SFT")
|
||||
|
||||
# Load preference data (chosen/rejected pairs)
|
||||
dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
|
||||
|
||||
# Configure training
|
||||
training_args = RewardConfig(
|
||||
output_dir="Qwen2.5-0.5B-Reward",
|
||||
per_device_train_batch_size=2,
|
||||
num_train_epochs=1,
|
||||
learning_rate=1e-5
|
||||
)
|
||||
|
||||
# Train reward model
|
||||
trainer = RewardTrainer(
|
||||
model=model,
|
||||
args=training_args,
|
||||
processing_class=tokenizer,
|
||||
train_dataset=dataset
|
||||
)
|
||||
trainer.train()
|
||||
trainer.save_model()
|
||||
```
|
||||
|
||||
**Step 3: RLOO reinforcement learning**
|
||||
|
||||
Optimize policy using the reward model. PPO was removed in TRL 1.x; use the RLOO CLI
|
||||
(`trl rloo`) with the trained reward model passed via `--reward_model_name_or_path`:
|
||||
|
||||
```bash
|
||||
trl rloo \
|
||||
--model_name_or_path Qwen2.5-0.5B-SFT \
|
||||
--reward_model_name_or_path Qwen2.5-0.5B-Reward \
|
||||
--dataset_name trl-internal-testing/descriptiveness-sentiment-trl-style \
|
||||
--output_dir Qwen2.5-0.5B-RLOO \
|
||||
--learning_rate 3e-6 \
|
||||
--per_device_train_batch_size 64 \
|
||||
--num_generations 4
|
||||
```
|
||||
|
||||
Equivalent Python (`RLOOTrainer` / `RLOOConfig`):
|
||||
```python
|
||||
from trl import RLOOTrainer, RLOOConfig
|
||||
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
||||
|
||||
reward_model = AutoModelForSequenceClassification.from_pretrained(
|
||||
"Qwen2.5-0.5B-Reward", num_labels=1
|
||||
)
|
||||
|
||||
config = RLOOConfig(
|
||||
output_dir="Qwen2.5-0.5B-RLOO",
|
||||
per_device_train_batch_size=64,
|
||||
learning_rate=3e-6,
|
||||
num_generations=4,
|
||||
)
|
||||
|
||||
trainer = RLOOTrainer(
|
||||
model="Qwen2.5-0.5B-SFT",
|
||||
reward_funcs=reward_model, # a reward model (or a callable reward function)
|
||||
args=config,
|
||||
train_dataset=dataset, # prompt-only dataset
|
||||
processing_class=tokenizer,
|
||||
)
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
**Step 4: Evaluate**
|
||||
|
||||
```python
|
||||
from transformers import pipeline
|
||||
|
||||
# Load aligned model
|
||||
generator = pipeline("text-generation", model="Qwen2.5-0.5B-RLOO")
|
||||
|
||||
# Test
|
||||
prompt = "Explain quantum computing to a 10-year-old"
|
||||
output = generator(prompt, max_length=200)[0]["generated_text"]
|
||||
print(output)
|
||||
```
|
||||
|
||||
### Workflow 2: Simple preference alignment with DPO
|
||||
|
||||
Align model with preferences without reward model.
|
||||
|
||||
Copy this checklist:
|
||||
|
||||
```
|
||||
DPO Training:
|
||||
- [ ] Step 1: Prepare preference dataset
|
||||
- [ ] Step 2: Configure DPO
|
||||
- [ ] Step 3: Train with DPOTrainer
|
||||
- [ ] Step 4: Evaluate alignment
|
||||
```
|
||||
|
||||
**Step 1: Prepare preference dataset**
|
||||
|
||||
Dataset format:
|
||||
```json
|
||||
{
|
||||
"prompt": "What is the capital of France?",
|
||||
"chosen": "The capital of France is Paris.",
|
||||
"rejected": "I don't know."
|
||||
}
|
||||
```
|
||||
|
||||
Load dataset:
|
||||
```python
|
||||
from datasets import load_dataset
|
||||
|
||||
dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
|
||||
# Or load your own
|
||||
# dataset = load_dataset("json", data_files="preferences.json")
|
||||
```
|
||||
|
||||
**Step 2: Configure DPO**
|
||||
|
||||
```python
|
||||
from trl import DPOConfig
|
||||
|
||||
config = DPOConfig(
|
||||
output_dir="Qwen2.5-0.5B-DPO",
|
||||
per_device_train_batch_size=4,
|
||||
num_train_epochs=1,
|
||||
learning_rate=5e-7,
|
||||
beta=0.1, # KL penalty strength
|
||||
max_prompt_length=512,
|
||||
max_length=1024,
|
||||
logging_steps=10
|
||||
)
|
||||
```
|
||||
|
||||
**Step 3: Train with DPOTrainer**
|
||||
|
||||
```python
|
||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||
from trl import DPOTrainer
|
||||
|
||||
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
|
||||
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
|
||||
|
||||
trainer = DPOTrainer(
|
||||
model=model,
|
||||
args=config,
|
||||
train_dataset=dataset,
|
||||
processing_class=tokenizer
|
||||
)
|
||||
|
||||
trainer.train()
|
||||
trainer.save_model()
|
||||
```
|
||||
|
||||
**CLI alternative**:
|
||||
```bash
|
||||
trl dpo \
|
||||
--model_name_or_path Qwen/Qwen2.5-0.5B-Instruct \
|
||||
--dataset_name argilla/Capybara-Preferences \
|
||||
--output_dir Qwen2.5-0.5B-DPO \
|
||||
--per_device_train_batch_size 4 \
|
||||
--learning_rate 5e-7 \
|
||||
--beta 0.1
|
||||
```
|
||||
|
||||
### Workflow 3: Memory-efficient online RL with GRPO
|
||||
|
||||
Train with reinforcement learning using minimal memory.
|
||||
|
||||
For in-depth GRPO guidance — reward function design, critical training insights (loss behavior, mode collapse, tuning), and advanced multi-stage patterns — see **[references/grpo-training.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\training\trl-fine-tuning/references/grpo-training.md)**. A production-ready training script is in **[templates/basic_grpo_training.py](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\training\trl-fine-tuning/templates/basic_grpo_training.py)**.
|
||||
|
||||
Copy this checklist:
|
||||
|
||||
```
|
||||
GRPO Training:
|
||||
- [ ] Step 1: Define reward function
|
||||
- [ ] Step 2: Configure GRPO
|
||||
- [ ] Step 3: Train with GRPOTrainer
|
||||
```
|
||||
|
||||
**Step 1: Define reward function**
|
||||
|
||||
```python
|
||||
def reward_function(completions, **kwargs):
|
||||
"""
|
||||
Compute rewards for completions.
|
||||
|
||||
Args:
|
||||
completions: List of generated texts
|
||||
|
||||
Returns:
|
||||
List of reward scores (floats)
|
||||
"""
|
||||
rewards = []
|
||||
for completion in completions:
|
||||
# Example: reward based on length and unique words
|
||||
score = len(completion.split()) # Favor longer responses
|
||||
score += len(set(completion.lower().split())) # Reward unique words
|
||||
rewards.append(score)
|
||||
return rewards
|
||||
```
|
||||
|
||||
Or use a reward model:
|
||||
```python
|
||||
from transformers import pipeline
|
||||
|
||||
reward_model = pipeline("text-classification", model="reward-model-path")
|
||||
|
||||
def reward_from_model(completions, prompts, **kwargs):
|
||||
# Combine prompt + completion
|
||||
full_texts = [p + c for p, c in zip(prompts, completions)]
|
||||
# Get reward scores
|
||||
results = reward_model(full_texts)
|
||||
return [r["score"] for r in results]
|
||||
```
|
||||
|
||||
**Step 2: Configure GRPO**
|
||||
|
||||
```python
|
||||
from trl import GRPOConfig
|
||||
|
||||
config = GRPOConfig(
|
||||
output_dir="Qwen2-GRPO",
|
||||
per_device_train_batch_size=4,
|
||||
num_train_epochs=1,
|
||||
learning_rate=1e-5,
|
||||
num_generations=4, # Generate 4 completions per prompt
|
||||
max_new_tokens=128
|
||||
)
|
||||
```
|
||||
|
||||
**Step 3: Train with GRPOTrainer**
|
||||
|
||||
```python
|
||||
from datasets import load_dataset
|
||||
from trl import GRPOTrainer
|
||||
|
||||
# Load prompt-only dataset
|
||||
dataset = load_dataset("trl-lib/tldr", split="train")
|
||||
|
||||
trainer = GRPOTrainer(
|
||||
model="Qwen/Qwen2-0.5B-Instruct",
|
||||
reward_funcs=reward_function, # Your reward function
|
||||
args=config,
|
||||
train_dataset=dataset
|
||||
)
|
||||
|
||||
trainer.train()
|
||||
```
|
||||
|
||||
**CLI**:
|
||||
```bash
|
||||
trl grpo \
|
||||
--model_name_or_path Qwen/Qwen2-0.5B-Instruct \
|
||||
--dataset_name trl-lib/tldr \
|
||||
--output_dir Qwen2-GRPO \
|
||||
--num_generations 4
|
||||
```
|
||||
|
||||
## When to use vs alternatives
|
||||
|
||||
**Use TRL when:**
|
||||
- Need to align model with human preferences
|
||||
- Have preference data (chosen/rejected pairs)
|
||||
- Want to use reinforcement learning (RLOO, GRPO)
|
||||
- Need reward model training
|
||||
- Doing RLHF (full pipeline)
|
||||
|
||||
**Method selection**:
|
||||
- **SFT**: Have prompt-completion pairs, want basic instruction following
|
||||
- **DPO**: Have preferences, want simple alignment (no reward model needed)
|
||||
- **RLOO**: Have a reward model, want online RL (the reward-model-driven RLHF path; PPO was removed in TRL 1.x)
|
||||
- **GRPO**: Memory-constrained, want online RL with reward functions
|
||||
- **Reward Model**: Building RLHF pipeline, need to score generations
|
||||
|
||||
**Use alternatives instead:**
|
||||
- **HuggingFace Trainer**: Basic fine-tuning without RL
|
||||
- **Axolotl**: YAML-based training configuration
|
||||
- **LitGPT**: Educational, minimal fine-tuning
|
||||
- **Unsloth**: Fast LoRA training
|
||||
|
||||
## Common issues
|
||||
|
||||
**Issue: OOM during DPO training**
|
||||
|
||||
Reduce batch size and sequence length:
|
||||
```python
|
||||
config = DPOConfig(
|
||||
per_device_train_batch_size=1, # Reduce from 4
|
||||
max_length=512, # Reduce from 1024
|
||||
gradient_accumulation_steps=8 # Maintain effective batch
|
||||
)
|
||||
```
|
||||
|
||||
Or use gradient checkpointing:
|
||||
```python
|
||||
model.gradient_checkpointing_enable()
|
||||
```
|
||||
|
||||
**Issue: Poor alignment quality**
|
||||
|
||||
Tune beta parameter:
|
||||
```python
|
||||
# Higher beta = more conservative (stays closer to reference)
|
||||
config = DPOConfig(beta=0.5) # Default 0.1
|
||||
|
||||
# Lower beta = more aggressive alignment
|
||||
config = DPOConfig(beta=0.01)
|
||||
```
|
||||
|
||||
**Issue: Reward model not learning**
|
||||
|
||||
Check loss type and learning rate:
|
||||
```python
|
||||
config = RewardConfig(
|
||||
learning_rate=1e-5, # Try different LR
|
||||
num_train_epochs=3 # Train longer
|
||||
)
|
||||
```
|
||||
|
||||
Ensure preference dataset has clear winners:
|
||||
```python
|
||||
# Verify dataset
|
||||
print(dataset[0])
|
||||
# Should have clear chosen > rejected
|
||||
```
|
||||
|
||||
**Issue: Online RL (RLOO/GRPO) training unstable**
|
||||
|
||||
Adjust the KL/beta regularization toward the reference policy:
|
||||
```python
|
||||
from trl import RLOOConfig
|
||||
|
||||
config = RLOOConfig(
|
||||
beta=0.05, # KL coefficient toward the reference model (increase for stability)
|
||||
num_generations=4, # more samples per prompt = lower-variance advantage estimates
|
||||
)
|
||||
```
|
||||
|
||||
## Advanced topics
|
||||
|
||||
**SFT training guide**: See [references/sft-training.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\training\trl-fine-tuning/references/sft-training.md) for dataset formats, chat templates, packing strategies, and multi-GPU training.
|
||||
|
||||
**DPO variants**: See [references/dpo-variants.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\training\trl-fine-tuning/references/dpo-variants.md) for IPO, cDPO, RPO, and other DPO loss functions with recommended hyperparameters.
|
||||
|
||||
**Reward modeling**: See [references/reward-modeling.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\training\trl-fine-tuning/references/reward-modeling.md) for outcome vs process rewards, Bradley-Terry loss, and reward model evaluation.
|
||||
|
||||
**Online RL methods**: See [references/online-rl.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\training\trl-fine-tuning/references/online-rl.md) for PPO, GRPO, RLOO, and OnlineDPO with detailed configurations.
|
||||
|
||||
**GRPO deep dive**: See [references/grpo-training.md](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\training\trl-fine-tuning/references/grpo-training.md) for expert-level GRPO patterns — reward function design philosophy, training insights (why loss increases, mode collapse detection), hyperparameter tuning, multi-stage training, and troubleshooting. Production-ready template in [templates/basic_grpo_training.py](https://github.com/NousResearch/hermes-agent/blob/main/optional-skills/mlops\training\trl-fine-tuning/templates/basic_grpo_training.py).
|
||||
|
||||
## Hardware requirements
|
||||
|
||||
- **GPU**: NVIDIA (CUDA required)
|
||||
- **VRAM**: Depends on model and method
|
||||
- SFT 7B: 16GB (with LoRA)
|
||||
- DPO 7B: 24GB (stores reference model)
|
||||
- RLOO 7B: 40GB (policy + reward model)
|
||||
- GRPO 7B: 24GB (more memory efficient)
|
||||
- **Multi-GPU**: Supported via `accelerate`
|
||||
- **Mixed precision**: BF16 recommended (A100/H100)
|
||||
|
||||
**Memory optimization**:
|
||||
- Use LoRA/QLoRA for all methods
|
||||
- Enable gradient checkpointing
|
||||
- Use smaller batch sizes with gradient accumulation
|
||||
|
||||
## Resources
|
||||
|
||||
- Docs: https://huggingface.co/docs/trl/
|
||||
- GitHub: https://github.com/huggingface/trl
|
||||
- Papers:
|
||||
- "Training language models to follow instructions with human feedback" (InstructGPT, 2022)
|
||||
- "Direct Preference Optimization: Your Language Model is Secretly a Reward Model" (DPO, 2023)
|
||||
- "Group Relative Policy Optimization" (GRPO, 2024)
|
||||
- Examples: https://github.com/huggingface/trl/tree/main/examples/scripts
|
||||
@@ -0,0 +1,98 @@
|
||||
---
|
||||
title: "Unsloth — Unsloth: 2-5x faster LoRA/QLoRA fine-tuning, less VRAM"
|
||||
sidebar_label: "Unsloth"
|
||||
description: "Unsloth: 2-5x faster LoRA/QLoRA fine-tuning, less VRAM"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Unsloth
|
||||
|
||||
Unsloth: 2-5x faster LoRA/QLoRA fine-tuning, less VRAM.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/unsloth` |
|
||||
| Path | `optional-skills/mlops\training\unsloth` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `unsloth`, `torch`, `transformers`, `trl`, `datasets`, `peft` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Fine-Tuning`, `Unsloth`, `Fast Training`, `LoRA`, `QLoRA`, `Memory-Efficient`, `Optimization`, `Llama`, `Mistral`, `Gemma`, `Qwen` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Unsloth Skill
|
||||
|
||||
Assistance with unsloth development, generated from official documentation.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
This skill should be triggered when:
|
||||
- Working with unsloth
|
||||
- Asking about unsloth features or APIs
|
||||
- Implementing unsloth solutions
|
||||
- Debugging unsloth code
|
||||
- Learning unsloth best practices
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Common Patterns
|
||||
|
||||
*Quick reference patterns will be added as you use the skill.*
|
||||
|
||||
## Reference Files
|
||||
|
||||
This skill includes full documentation in `references/`:
|
||||
|
||||
- **llms-txt.md** - Llms-Txt documentation
|
||||
|
||||
Use `view` to read specific reference files when detailed information is needed.
|
||||
|
||||
## Working with This Skill
|
||||
|
||||
### For Beginners
|
||||
Start with the getting_started or tutorials reference files for foundational concepts.
|
||||
|
||||
### For Specific Features
|
||||
Use the appropriate category reference file (api, guides, etc.) for detailed information.
|
||||
|
||||
### For Code Examples
|
||||
The quick reference section above contains common patterns extracted from the official docs.
|
||||
|
||||
## Resources
|
||||
|
||||
### references/
|
||||
Organized documentation extracted from official sources. These files contain:
|
||||
- Detailed explanations
|
||||
- Code examples with language annotations
|
||||
- Links to original documentation
|
||||
- Table of contents for quick navigation
|
||||
|
||||
### scripts/
|
||||
Add helper scripts here for common automation tasks.
|
||||
|
||||
### assets/
|
||||
Add templates, boilerplate, or example projects here.
|
||||
|
||||
## Notes
|
||||
|
||||
- This skill was automatically generated from official documentation
|
||||
- Reference files preserve the structure and examples from source docs
|
||||
- Code examples include language detection for better syntax highlighting
|
||||
- Quick reference patterns are extracted from common usage examples in the docs
|
||||
|
||||
## Updating
|
||||
|
||||
To refresh this skill with updated documentation:
|
||||
1. Re-run the scraper with the same configuration
|
||||
2. The skill will be rebuilt with the latest information
|
||||
|
||||
<!-- Trigger re-upload 1763621536 -->
|
||||
@@ -0,0 +1,336 @@
|
||||
---
|
||||
title: "Whisper — Transcribe and translate speech in 99 languages"
|
||||
sidebar_label: "Whisper"
|
||||
description: "Transcribe and translate speech in 99 languages"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Whisper
|
||||
|
||||
Transcribe and translate speech in 99 languages.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/mlops/whisper` |
|
||||
| Path | `optional-skills/mlops\whisper` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Orchestra Research |
|
||||
| License | MIT |
|
||||
| Dependencies | `openai-whisper`, `transformers`, `torch` |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Whisper`, `Speech Recognition`, `ASR`, `Multimodal`, `Multilingual`, `OpenAI`, `Speech-To-Text`, `Transcription`, `Translation`, `Audio Processing` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Whisper - Robust Speech Recognition
|
||||
|
||||
OpenAI's multilingual speech recognition model.
|
||||
|
||||
## When to use Whisper
|
||||
|
||||
**Use when:**
|
||||
- Speech-to-text transcription (99 languages)
|
||||
- Podcast/video transcription
|
||||
- Meeting notes automation
|
||||
- Translation to English
|
||||
- Noisy audio transcription
|
||||
- Multilingual audio processing
|
||||
|
||||
**Metrics**:
|
||||
- **72,900+ GitHub stars**
|
||||
- 99 languages supported
|
||||
- Trained on 680,000 hours of audio
|
||||
- MIT License
|
||||
|
||||
**Use alternatives instead**:
|
||||
- **AssemblyAI**: Managed API, speaker diarization
|
||||
- **Deepgram**: Real-time streaming ASR
|
||||
- **Google Speech-to-Text**: Cloud-based
|
||||
|
||||
## Quick start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Requires Python 3.8-3.11
|
||||
pip install -U openai-whisper
|
||||
|
||||
# Requires ffmpeg
|
||||
# macOS: brew install ffmpeg
|
||||
# Ubuntu: sudo apt install ffmpeg
|
||||
# Windows: choco install ffmpeg
|
||||
```
|
||||
|
||||
### Basic transcription
|
||||
|
||||
```python
|
||||
import whisper
|
||||
|
||||
# Load model
|
||||
model = whisper.load_model("base")
|
||||
|
||||
# Transcribe
|
||||
result = model.transcribe("audio.mp3")
|
||||
|
||||
# Print text
|
||||
print(result["text"])
|
||||
|
||||
# Access segments
|
||||
for segment in result["segments"]:
|
||||
print(f"[{segment['start']:.2f}s - {segment['end']:.2f}s] {segment['text']}")
|
||||
```
|
||||
|
||||
## Model sizes
|
||||
|
||||
```python
|
||||
# Available models
|
||||
models = ["tiny", "base", "small", "medium", "large", "turbo"]
|
||||
|
||||
# Load specific model
|
||||
model = whisper.load_model("turbo") # Fastest, good quality
|
||||
```
|
||||
|
||||
| Model | Parameters | English-only | Multilingual | Speed | VRAM |
|
||||
|-------|------------|--------------|--------------|-------|------|
|
||||
| tiny | 39M | ✓ | ✓ | ~32x | ~1 GB |
|
||||
| base | 74M | ✓ | ✓ | ~16x | ~1 GB |
|
||||
| small | 244M | ✓ | ✓ | ~6x | ~2 GB |
|
||||
| medium | 769M | ✓ | ✓ | ~2x | ~5 GB |
|
||||
| large | 1550M | ✗ | ✓ | 1x | ~10 GB |
|
||||
| turbo | 809M | ✗ | ✓ | ~8x | ~6 GB |
|
||||
|
||||
**Recommendation**: Use `turbo` for best speed/quality, `base` for prototyping
|
||||
|
||||
## Transcription options
|
||||
|
||||
### Language specification
|
||||
|
||||
```python
|
||||
# Auto-detect language
|
||||
result = model.transcribe("audio.mp3")
|
||||
|
||||
# Specify language (faster)
|
||||
result = model.transcribe("audio.mp3", language="en")
|
||||
|
||||
# Supported: en, es, fr, de, it, pt, ru, ja, ko, zh, and 89 more
|
||||
```
|
||||
|
||||
### Task selection
|
||||
|
||||
```python
|
||||
# Transcription (default)
|
||||
result = model.transcribe("audio.mp3", task="transcribe")
|
||||
|
||||
# Translation to English
|
||||
result = model.transcribe("spanish.mp3", task="translate")
|
||||
# Input: Spanish audio → Output: English text
|
||||
```
|
||||
|
||||
### Initial prompt
|
||||
|
||||
```python
|
||||
# Improve accuracy with context
|
||||
result = model.transcribe(
|
||||
"audio.mp3",
|
||||
initial_prompt="This is a technical podcast about machine learning and AI."
|
||||
)
|
||||
|
||||
# Helps with:
|
||||
# - Technical terms
|
||||
# - Proper nouns
|
||||
# - Domain-specific vocabulary
|
||||
```
|
||||
|
||||
### Timestamps
|
||||
|
||||
```python
|
||||
# Word-level timestamps
|
||||
result = model.transcribe("audio.mp3", word_timestamps=True)
|
||||
|
||||
for segment in result["segments"]:
|
||||
for word in segment["words"]:
|
||||
print(f"{word['word']} ({word['start']:.2f}s - {word['end']:.2f}s)")
|
||||
```
|
||||
|
||||
### Temperature fallback
|
||||
|
||||
```python
|
||||
# Retry with different temperatures if confidence low
|
||||
result = model.transcribe(
|
||||
"audio.mp3",
|
||||
temperature=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
|
||||
)
|
||||
```
|
||||
|
||||
## Command line usage
|
||||
|
||||
```bash
|
||||
# Basic transcription
|
||||
whisper audio.mp3
|
||||
|
||||
# Specify model
|
||||
whisper audio.mp3 --model turbo
|
||||
|
||||
# Output formats
|
||||
whisper audio.mp3 --output_format txt # Plain text
|
||||
whisper audio.mp3 --output_format srt # Subtitles
|
||||
whisper audio.mp3 --output_format vtt # WebVTT
|
||||
whisper audio.mp3 --output_format json # JSON with timestamps
|
||||
|
||||
# Language
|
||||
whisper audio.mp3 --language Spanish
|
||||
|
||||
# Translation
|
||||
whisper spanish.mp3 --task translate
|
||||
```
|
||||
|
||||
## Batch processing
|
||||
|
||||
```python
|
||||
import os
|
||||
|
||||
audio_files = ["file1.mp3", "file2.mp3", "file3.mp3"]
|
||||
|
||||
for audio_file in audio_files:
|
||||
print(f"Transcribing {audio_file}...")
|
||||
result = model.transcribe(audio_file)
|
||||
|
||||
# Save to file
|
||||
output_file = audio_file.replace(".mp3", ".txt")
|
||||
with open(output_file, "w") as f:
|
||||
f.write(result["text"])
|
||||
```
|
||||
|
||||
## Real-time transcription
|
||||
|
||||
```python
|
||||
# For streaming audio, use faster-whisper
|
||||
# pip install faster-whisper
|
||||
|
||||
from faster_whisper import WhisperModel
|
||||
|
||||
model = WhisperModel("base", device="cuda", compute_type="float16")
|
||||
|
||||
# Transcribe with streaming
|
||||
segments, info = model.transcribe("audio.mp3", beam_size=5)
|
||||
|
||||
for segment in segments:
|
||||
print(f"[{segment.start:.2f}s -> {segment.end:.2f}s] {segment.text}")
|
||||
```
|
||||
|
||||
## GPU acceleration
|
||||
|
||||
```python
|
||||
import whisper
|
||||
|
||||
# Automatically uses GPU if available
|
||||
model = whisper.load_model("turbo")
|
||||
|
||||
# Force CPU
|
||||
model = whisper.load_model("turbo", device="cpu")
|
||||
|
||||
# Force GPU
|
||||
model = whisper.load_model("turbo", device="cuda")
|
||||
|
||||
# 10-20× faster on GPU
|
||||
```
|
||||
|
||||
## Integration with other tools
|
||||
|
||||
### Subtitle generation
|
||||
|
||||
```bash
|
||||
# Generate SRT subtitles
|
||||
whisper video.mp4 --output_format srt --language English
|
||||
|
||||
# Output: video.srt
|
||||
```
|
||||
|
||||
### With LangChain
|
||||
|
||||
```python
|
||||
from langchain.document_loaders import WhisperTranscriptionLoader
|
||||
|
||||
loader = WhisperTranscriptionLoader(file_path="audio.mp3")
|
||||
docs = loader.load()
|
||||
|
||||
# Use transcription in RAG
|
||||
from langchain_chroma import Chroma
|
||||
from langchain_openai import OpenAIEmbeddings
|
||||
|
||||
vectorstore = Chroma.from_documents(docs, OpenAIEmbeddings())
|
||||
```
|
||||
|
||||
### Extract audio from video
|
||||
|
||||
```bash
|
||||
# Use ffmpeg to extract audio
|
||||
ffmpeg -i video.mp4 -vn -acodec pcm_s16le audio.wav
|
||||
|
||||
# Then transcribe
|
||||
whisper audio.wav
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
1. **Use turbo model** - Best speed/quality for English
|
||||
2. **Specify language** - Faster than auto-detect
|
||||
3. **Add initial prompt** - Improves technical terms
|
||||
4. **Use GPU** - 10-20× faster
|
||||
5. **Batch process** - More efficient
|
||||
6. **Convert to WAV** - Better compatibility
|
||||
7. **Split long audio** - <30 min chunks
|
||||
8. **Check language support** - Quality varies by language
|
||||
9. **Use faster-whisper** - 4× faster than openai-whisper
|
||||
10. **Monitor VRAM** - Scale model size to hardware
|
||||
|
||||
## Performance
|
||||
|
||||
| Model | Real-time factor (CPU) | Real-time factor (GPU) |
|
||||
|-------|------------------------|------------------------|
|
||||
| tiny | ~0.32 | ~0.01 |
|
||||
| base | ~0.16 | ~0.01 |
|
||||
| turbo | ~0.08 | ~0.01 |
|
||||
| large | ~1.0 | ~0.05 |
|
||||
|
||||
*Real-time factor: 0.1 = 10× faster than real-time*
|
||||
|
||||
## Language support
|
||||
|
||||
Top-supported languages:
|
||||
- English (en)
|
||||
- Spanish (es)
|
||||
- French (fr)
|
||||
- German (de)
|
||||
- Italian (it)
|
||||
- Portuguese (pt)
|
||||
- Russian (ru)
|
||||
- Japanese (ja)
|
||||
- Korean (ko)
|
||||
- Chinese (zh)
|
||||
|
||||
Full list: 99 languages total
|
||||
|
||||
## Limitations
|
||||
|
||||
1. **Hallucinations** - May repeat or invent text
|
||||
2. **Long-form accuracy** - Degrades on >30 min audio
|
||||
3. **Speaker identification** - No diarization
|
||||
4. **Accents** - Quality varies
|
||||
5. **Background noise** - Can affect accuracy
|
||||
6. **Real-time latency** - Not suitable for live captioning
|
||||
|
||||
## Resources
|
||||
|
||||
- **GitHub**: https://github.com/openai/whisper ⭐ 72,900+
|
||||
- **Paper**: https://arxiv.org/abs/2212.04356
|
||||
- **Model Card**: https://github.com/openai/whisper/blob/main/model-card.md
|
||||
- **Colab**: Available in repo
|
||||
- **License**: MIT
|
||||
@@ -0,0 +1,142 @@
|
||||
---
|
||||
title: "Mpp Agent — Pay HTTP 402 APIs via Machine Payments Protocol (MPP)"
|
||||
sidebar_label: "Mpp Agent"
|
||||
description: "Pay HTTP 402 APIs via Machine Payments Protocol (MPP)"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Mpp Agent
|
||||
|
||||
Pay HTTP 402 APIs via Machine Payments Protocol (MPP).
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/payments/mpp-agent` |
|
||||
| Path | `optional-skills/payments\mpp-agent` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | Teknium (teknium1), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Payments`, `MPP`, `HTTP-402`, `Tempo`, `Stripe` |
|
||||
| Related skills | [`stripe-link-cli`](/docs/user-guide/skills/optional/payments/payments-stripe-link-cli), [`stripe-projects`](/docs/user-guide/skills/optional/payments/payments-stripe-projects) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# MPP Agent Skill
|
||||
|
||||
Wraps the Machine Payments Protocol (MPP, https://mpp.dev) clients so Hermes can pay for per-request API access against servers that respond with `HTTP 402 Payment Required`.
|
||||
|
||||
Three client options, all distributed via npm. Pick the lightest one that solves the user's need. Gated `[linux, macos]` while the broader payments tooling matures on Windows.
|
||||
|
||||
## When to Use
|
||||
|
||||
- A merchant API returns `HTTP 402` with a `www-authenticate` header — and the user wants to actually pay it, not just log the response.
|
||||
- The user asks to "pay per request", "set up an agent wallet", "use Tempo / Privy / AgentCash", or wants to discover MPP-priced services.
|
||||
- A Stripe Link spend has produced a Shared Payment Token (SPT) and the agent needs to attach it to the 402 challenge — in that flow, prefer `link-cli mpp pay` (see the `stripe-link-cli` skill).
|
||||
|
||||
## Choosing a client
|
||||
|
||||
| Tool | When | Setup |
|
||||
|---|---|---|
|
||||
| `link-cli` | User already has Stripe Link set up, or the 402 challenge advertises `method="stripe"` | see the `stripe-link-cli` skill |
|
||||
| Tempo Wallet | MPP services with spend controls, service discovery | `tempo wallet login` |
|
||||
| Privy Agent CLI | Multi-chain wallets, browser-based funding | `privy-agent-wallets login` |
|
||||
| AgentCash | 300+ pre-priced APIs via one USDC.e balance | `npx agentcash onboard` |
|
||||
| `mppx` | Dev + debugging, smallest dep surface | `npm install -g mppx` then `mppx account create` |
|
||||
|
||||
Default: if the user already has Stripe Link configured or the 402 challenge specifies `method="stripe"`, use `link-cli mpp pay` (the `stripe-link-cli` skill). Otherwise `mppx` for one-off paid calls and debugging, and Tempo Wallet when the user wants persistent spend controls.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 20+ on `PATH`
|
||||
- A funded wallet (Tempo / Privy / AgentCash) OR an `mppx` account
|
||||
- For Tempo / Privy / AgentCash: follow their respective onboarding skills:
|
||||
- `https://tempo.xyz/SKILL.md`
|
||||
- `https://agents.privy.io/skill.md`
|
||||
- `https://agentcash.dev/skill.md`
|
||||
|
||||
Use `web_extract` to fetch any of those SKILL.md files if the user picks one.
|
||||
|
||||
## Procedure (mppx, fastest path)
|
||||
|
||||
Run all commands through the `terminal` tool.
|
||||
|
||||
### 1. Install + create an account
|
||||
|
||||
```
|
||||
npm install -g mppx
|
||||
mppx account create
|
||||
```
|
||||
|
||||
Store the resulting account credentials wherever the CLI tells you (the CLI writes them under its own config — do not paste them into the agent transcript).
|
||||
|
||||
### 2. Inspect the merchant's 402 challenge
|
||||
|
||||
If the user gives you a URL, probe it first to confirm it actually speaks MPP:
|
||||
|
||||
```
|
||||
curl -i <url>
|
||||
```
|
||||
|
||||
A real MPP 402 looks like:
|
||||
|
||||
```
|
||||
HTTP/1.1 402 Payment Required
|
||||
www-authenticate: tempo amount=0.1 currency=...
|
||||
```
|
||||
|
||||
### 3. Pay the request
|
||||
|
||||
```
|
||||
mppx <url>
|
||||
```
|
||||
|
||||
For non-GET methods or request bodies:
|
||||
|
||||
```
|
||||
mppx <url> --method POST --data '<json>'
|
||||
```
|
||||
|
||||
`mppx` handles the 402 challenge/credential dance automatically and prints the merchant's actual response on success.
|
||||
|
||||
### 4. Verify the receipt
|
||||
|
||||
`mppx` attaches the receipt header automatically. To inspect:
|
||||
|
||||
```
|
||||
mppx <url> -v
|
||||
```
|
||||
|
||||
## Procedure (Tempo Wallet)
|
||||
|
||||
The Tempo Wallet skill at https://tempo.xyz/SKILL.md is the canonical reference; fetch it with `web_extract` and follow it. Headline:
|
||||
|
||||
```
|
||||
tempo wallet login
|
||||
tempo wallet pay <url>
|
||||
```
|
||||
|
||||
Spend controls and service discovery live in the wallet UI at https://wallet.tempo.xyz.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **`HTTP 402` without `method="stripe"` cannot be paid by Stripe Link.** If the challenge advertises only Tempo / other methods, use `mppx` (or whichever wallet matches) — Link will reject it. Conversely, if it advertises `method="stripe"`, prefer Link via the `stripe-link-cli` skill so the spend goes through the user's approved card.
|
||||
- **Multiple challenges in one header.** `www-authenticate` may list several methods (e.g. `tempo, stripe`). The Link CLI's `mpp decode` will pick the Stripe one; `mppx` will pick Tempo. There's no single "right" client — pick by which wallet the user has funded.
|
||||
- **Zero-amount challenges.** Some MPP endpoints charge `$0.00` and just want a proof credential. These work without a funded wallet. Don't refuse them as "broken."
|
||||
- **Wallet keys never enter agent context.** All four clients store keys under their own config dirs (or generate per-session ephemeral keypairs, in Privy's case). Do not `cat`/`read_file` them.
|
||||
- **Server-side MPP is a different skill.** If the user wants to ADD 402 to their own API, this skill is wrong — point them at https://mpp.dev/quickstart/server and the `mppx/nextjs` / `mppx/hono` / `mppx/express` / `mppx/elysia` middlewares. A dedicated `mpp-server` skill may land later.
|
||||
|
||||
## Verification
|
||||
|
||||
```
|
||||
mppx --version && mppx account list
|
||||
```
|
||||
|
||||
Exit code 0 means installed and an account exists.
|
||||
@@ -0,0 +1,202 @@
|
||||
---
|
||||
title: "Stripe Link Cli — Agent payments via Stripe Link — cards, SPT, approvals"
|
||||
sidebar_label: "Stripe Link Cli"
|
||||
description: "Agent payments via Stripe Link — cards, SPT, approvals"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Stripe Link Cli
|
||||
|
||||
Agent payments via Stripe Link — cards, SPT, approvals.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/payments/stripe-link-cli` |
|
||||
| Path | `optional-skills/payments\stripe-link-cli` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | Teknium (teknium1), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Payments`, `Stripe`, `Link`, `Checkout`, `MPP` |
|
||||
| Related skills | [`mpp-agent`](/docs/user-guide/skills/optional/payments/payments-mpp-agent), [`stripe-projects`](/docs/user-guide/skills/optional/payments/payments-stripe-projects) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Stripe Link CLI Skill
|
||||
|
||||
Wraps [@stripe/link-cli](https://github.com/stripe/link-cli) so Hermes can complete purchases on the user's behalf using one-time-use virtual cards or Shared Payment Tokens (SPT). Every spend is gated by an in-app approval in the Link mobile/web app — Hermes cannot self-approve.
|
||||
|
||||
US-only at the moment (Link account requirement). Windows is not supported by the upstream CLI — this skill is gated `[linux, macos]`.
|
||||
|
||||
## When to Use
|
||||
|
||||
Trigger phrases:
|
||||
|
||||
- "buy X", "pay for X", "make a purchase", "complete checkout"
|
||||
- "get me a card", "I need a payment method"
|
||||
- "log in to Link", "connect my Link wallet"
|
||||
- HTTP 402 response from a merchant API with `www-authenticate: ... method="stripe"`
|
||||
|
||||
If the user wants a paid API call (HTTP 402, no checkout form), the `card` path is wrong — use SPT via this same skill, or hand off to the `mpp-agent` skill.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 20+ available on `PATH` (`node --version`)
|
||||
- US-based (Link account requirement)
|
||||
|
||||
The Link account, payment method, and spend-approval app do NOT need to be set up before Hermes attempts to pay — the CLI walks the user through them on first run:
|
||||
|
||||
- A Link account at https://app.link.com — created/linked during first `link-cli` auth
|
||||
- At least one payment method — added during first run at https://app.link.com/wallet
|
||||
- The Link mobile/web app — opened to approve the first spend request when it's made
|
||||
|
||||
No env vars required — auth state is stored locally by the CLI under its own config directory.
|
||||
|
||||
## Install
|
||||
|
||||
Install once, globally:
|
||||
|
||||
```
|
||||
npm install -g @stripe/link-cli
|
||||
```
|
||||
|
||||
Or invoke ad-hoc via `npx @stripe/link-cli`. The skill below uses the installed `link-cli` form.
|
||||
|
||||
## How to Run
|
||||
|
||||
All commands run through the `terminal` tool. The CLI auto-detects non-TTY callers and emits compact `toon` output by default — fine for the model. Pass `--format json` if a step needs structured fields.
|
||||
|
||||
Discover commands: `link-cli --llms-full`.
|
||||
Get a command's schema before invoking: `link-cli <command> --schema`.
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Check / establish auth
|
||||
|
||||
```
|
||||
link-cli auth status
|
||||
```
|
||||
|
||||
If not authenticated, log in with a clear client name (this label shows in the user's Link app):
|
||||
|
||||
```
|
||||
link-cli auth login --client-name "Hermes" --interval 5 --timeout 300
|
||||
```
|
||||
|
||||
The `--interval`/`--timeout` form polls inline so the agent doesn't need to manage a `_next` step. Print the verification URL + phrase to the user and wait for the CLI to return.
|
||||
|
||||
**Do not proceed past this step until `auth status` confirms login.**
|
||||
|
||||
### 2. Evaluate the merchant before creating a spend request
|
||||
|
||||
Decide the credential type:
|
||||
|
||||
| Merchant surface | `--credential-type` |
|
||||
|---|---|
|
||||
| Standard web checkout form / Stripe Elements | `card` (default) |
|
||||
| Returns HTTP 402 with `method="stripe"` in `www-authenticate` | `shared_payment_token` |
|
||||
| Returns HTTP 402 without `method="stripe"` | unsupported — stop |
|
||||
|
||||
For 402 responses, do NOT decode the challenge manually. Pass the raw header:
|
||||
|
||||
```
|
||||
link-cli mpp decode --challenge '<full WWW-Authenticate header>'
|
||||
```
|
||||
|
||||
This validates the challenge and extracts the network ID + decoded request body.
|
||||
|
||||
### 3. List payment methods + shipping
|
||||
|
||||
```
|
||||
link-cli payment-methods list
|
||||
link-cli shipping-address list
|
||||
```
|
||||
|
||||
Use the first entry unless the user specifies otherwise. The `id` from `payment-methods list` is the `--payment-method-id` in the next step.
|
||||
|
||||
### 4. Create the spend request
|
||||
|
||||
Confirm the final total with the user before issuing this command. Amounts are in cents.
|
||||
|
||||
```
|
||||
link-cli spend-request create \
|
||||
--payment-method-id <pm_id> \
|
||||
--merchant-name "<name>" \
|
||||
--merchant-url "<url>" \
|
||||
--context "<one sentence: what is being purchased and why>" \
|
||||
--amount <cents> \
|
||||
--line-item "name:<item>,unit_amount:<cents>,quantity:1" \
|
||||
--total "type:total,display_text:Total,amount:<cents>" \
|
||||
--request-approval
|
||||
```
|
||||
|
||||
For MPP merchants add `--credential-type shared_payment_token`.
|
||||
|
||||
`--request-approval` pings the user's Link app and polls until they approve or deny. The CLI exits non-zero on deny / timeout.
|
||||
|
||||
### 5. Retrieve the credential — SECURELY
|
||||
|
||||
**Do not print card details to stdout.** Use `--output-file` so the PAN never enters the agent's transcript or logs:
|
||||
|
||||
```
|
||||
link-cli spend-request retrieve <lsrq_id> \
|
||||
--include card \
|
||||
--output-file /tmp/link-card.json \
|
||||
--format json
|
||||
```
|
||||
|
||||
The file is written with `0600` perms; stdout shows only redacted fields (brand, last4, expiry) plus a `card_output_file` path.
|
||||
|
||||
### 6. Use the credential
|
||||
|
||||
- For web checkout: hand the file path to the user, OR pass it to a browser-driving tool that fills the form directly from disk. Never `read_file` or `cat` the card file into the agent's reasoning context.
|
||||
- For MPP merchants:
|
||||
|
||||
```
|
||||
link-cli mpp pay <merchant-url> \
|
||||
--spend-request-id <lsrq_id> \
|
||||
--method POST \
|
||||
--data '<json body>'
|
||||
```
|
||||
|
||||
### 7. Clean up
|
||||
|
||||
Delete the card file as soon as the purchase is done:
|
||||
|
||||
```
|
||||
rm -f /tmp/link-card.json
|
||||
```
|
||||
|
||||
## Optional: run as an MCP server instead
|
||||
|
||||
`@stripe/link-cli --mcp` exposes the same commands as MCP tools over stdio. To register it with Hermes' native MCP:
|
||||
|
||||
```
|
||||
hermes mcp add stripe-link --command "npx" --args "@stripe/link-cli --mcp"
|
||||
```
|
||||
|
||||
Then `hermes mcp list` should show `stripe-link`. The same approval rules apply — MCP doesn't bypass the Link app approval step.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **US-only.** Outside the US, `auth login` will fail. Tell the user, don't keep retrying.
|
||||
- **Card PAN must never enter agent context.** Use `--output-file` every time. If you've already retrieved without it, immediately `link-cli auth logout` is not enough — the card is one-time-use but rotate hygiene matters.
|
||||
- **`--request-approval` blocks until the user acts.** If the user is asleep, the CLI will hit its timeout. Set expectations.
|
||||
- **Multi-step `_next` commands.** Some commands return `_next.command` that must be executed to continue. When in doubt, prefer the inline-polling flags (`--interval`/`--timeout`).
|
||||
- **Output format defaults to `toon`** in non-TTY mode. Fine for prose, but if a downstream step needs to parse a specific field, pass `--format json`.
|
||||
- **Don't default to `card`.** The merchant-evaluation step (Section 2) exists because picking the wrong credential type fails the purchase silently or leaks more data than needed.
|
||||
|
||||
## Verification
|
||||
|
||||
```
|
||||
link-cli --version && link-cli auth status
|
||||
```
|
||||
|
||||
Exit code 0 means installed and logged in.
|
||||
@@ -0,0 +1,138 @@
|
||||
---
|
||||
title: "Stripe Projects — Provision SaaS services + sync creds via Stripe Projects"
|
||||
sidebar_label: "Stripe Projects"
|
||||
description: "Provision SaaS services + sync creds via Stripe Projects"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Stripe Projects
|
||||
|
||||
Provision SaaS services + sync creds via Stripe Projects.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/payments/stripe-projects` |
|
||||
| Path | `optional-skills/payments\stripe-projects` |
|
||||
| Version | `0.1.0` |
|
||||
| Author | Teknium (teknium1), Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos |
|
||||
| Tags | `Payments`, `Stripe`, `Projects`, `Provisioning`, `Infrastructure` |
|
||||
| Related skills | [`stripe-link-cli`](/docs/user-guide/skills/optional/payments/payments-stripe-link-cli), [`mpp-agent`](/docs/user-guide/skills/optional/payments/payments-mpp-agent) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Stripe Projects Skill
|
||||
|
||||
Wraps the [Stripe Projects](https://projects.dev) CLI plugin so Hermes can provision SaaS services (Neon, Twilio, Vercel, etc.), generate and sync credentials into the user's `.env`, and manage billing across providers from one place.
|
||||
|
||||
Gated `[linux, macos]` while the broader payments cluster matures on Windows. The Stripe CLI itself is cross-platform; this gate is a posture for the cluster, not a hard limit.
|
||||
|
||||
## When to Use
|
||||
|
||||
Trigger phrases:
|
||||
|
||||
- "set up <provider>", "provision <Neon|Twilio|Vercel|...>", "create a database"
|
||||
- "give me a <Postgres|Redis|Twilio number|...> for this project"
|
||||
- "manage my stack credentials", "rotate this key", "upgrade my plan"
|
||||
- "what providers can I add?"
|
||||
|
||||
If the user already has a provider account, this skill can still connect it with `stripe projects link <provider>`. If the user wants to use an existing provider resource, such as an existing database or Vercel project, check provider support first; many providers currently support provisioning new resources but not importing existing ones.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Stripe CLI installed (Homebrew on macOS, package manager on Linux, or download from https://docs.stripe.com/stripe-cli/install)
|
||||
- Stripe Projects plugin installed
|
||||
- A Stripe account. If the user doesn't have one yet, the CLI can guide them through sign-in or account creation in the browser during setup.
|
||||
|
||||
## Install
|
||||
|
||||
macOS:
|
||||
|
||||
```
|
||||
brew install stripe/stripe-cli/stripe
|
||||
stripe plugin install projects
|
||||
```
|
||||
|
||||
Linux: follow the platform-specific install at https://docs.stripe.com/stripe-cli/install, then:
|
||||
|
||||
```
|
||||
stripe plugin install projects
|
||||
```
|
||||
|
||||
## How to Run
|
||||
|
||||
All commands run through the `terminal` tool from inside the user's project directory (the CLI writes `.env` and `.projects/vault/vault.json` into the CWD).
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Initialize the project
|
||||
|
||||
```
|
||||
cd <project-root>
|
||||
stripe projects init
|
||||
```
|
||||
|
||||
This creates `.projects/vault/vault.json` (encrypted credential store) and prepares the project to receive providers.
|
||||
|
||||
### 2. Discover available providers
|
||||
|
||||
```
|
||||
stripe projects catalog
|
||||
```
|
||||
|
||||
Lists every provider Stripe Projects supports — databases, hosting, auth, AI, analytics, messaging, etc.
|
||||
|
||||
### 3. Add a service
|
||||
|
||||
```
|
||||
stripe projects add <provider>/<service>
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
- `stripe projects add neon/postgres`
|
||||
- `stripe projects add twilio/sms`
|
||||
- `stripe projects add runloop/sandbox`
|
||||
|
||||
The CLI provisions the service in the user's own account with the provider, generates credentials, syncs them into `.env`, and records the resource in the vault. The user may need to confirm a tier selection or pricing prompt.
|
||||
|
||||
### 4. Verify
|
||||
|
||||
```
|
||||
stripe projects list
|
||||
```
|
||||
|
||||
Should show the newly added provider and its `.env` keys.
|
||||
|
||||
### 5. Manage / upgrade / remove
|
||||
|
||||
```
|
||||
stripe projects upgrade <provider> # tier change
|
||||
stripe projects remove <provider> # deprovision
|
||||
stripe projects rotate <provider> # rotate credentials
|
||||
```
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **`.env` writes are real writes.** The CLI appends to whatever `.env` is in the project root. If the user's `.env` is gitignored (normal), the keys land safely; if not, this skill could be a credential-leak vector. Always check `.gitignore` first.
|
||||
- **Per-project state.** `.projects/vault/vault.json` is per-project. Provisioning the same service in two different projects creates two separate resources — and two bills.
|
||||
- **Billing happens on Stripe's side.** Tier prompts during `add`/`upgrade` are real charges; surface them to the user before confirming.
|
||||
- **Provider availability changes.** The catalog grows; if a provider the user names isn't listed, `stripe projects catalog | grep <name>` first instead of failing the `add` call.
|
||||
- **Credentials in vault are encrypted but `.env` is plaintext.** Standard `.env` hygiene applies — never commit it.
|
||||
- **Removing a service does NOT always destroy the underlying resource.** Some providers leave a paused/dormant resource behind. Check the provider's own dashboard after `remove` for high-cost services (managed databases especially).
|
||||
|
||||
## Verification
|
||||
|
||||
```
|
||||
stripe projects --version && stripe projects list
|
||||
```
|
||||
|
||||
Exit code 0 inside an initialized project means the plugin is healthy.
|
||||
@@ -0,0 +1,114 @@
|
||||
---
|
||||
title: "Canvas — Fetch Canvas LMS courses and assignments via API token"
|
||||
sidebar_label: "Canvas"
|
||||
description: "Fetch Canvas LMS courses and assignments via API token"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Canvas
|
||||
|
||||
Fetch Canvas LMS courses and assignments via API token.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/productivity/canvas` |
|
||||
| Path | `optional-skills/productivity\canvas` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | community |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `Canvas`, `LMS`, `Education`, `Courses`, `Assignments` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Canvas LMS — Course & Assignment Access
|
||||
|
||||
Read-only access to Canvas LMS for listing courses and assignments.
|
||||
|
||||
## Scripts
|
||||
|
||||
- `scripts/canvas_api.py` — Python CLI for Canvas API calls
|
||||
|
||||
## Setup
|
||||
|
||||
1. Log in to your Canvas instance in a browser
|
||||
2. Go to **Account → Settings** (click your profile icon, then Settings)
|
||||
3. Scroll to **Approved Integrations** and click **+ New Access Token**
|
||||
4. Name the token (e.g., "Hermes Agent"), set an optional expiry, and click **Generate Token**
|
||||
5. Copy the token and add to `${HERMES_HOME:-~/.hermes}/.env`:
|
||||
|
||||
```
|
||||
CANVAS_API_TOKEN=your_token_here
|
||||
CANVAS_BASE_URL=https://yourschool.instructure.com
|
||||
```
|
||||
|
||||
The base URL is whatever appears in your browser when you're logged into Canvas (no trailing slash).
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
CANVAS="python $HERMES_HOME/skills/productivity/canvas/scripts/canvas_api.py"
|
||||
|
||||
# List all active courses
|
||||
$CANVAS list_courses --enrollment-state active
|
||||
|
||||
# List all courses (any state)
|
||||
$CANVAS list_courses
|
||||
|
||||
# List assignments for a specific course
|
||||
$CANVAS list_assignments 12345
|
||||
|
||||
# List assignments ordered by due date
|
||||
$CANVAS list_assignments 12345 --order-by due_at
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
**list_courses** returns:
|
||||
```json
|
||||
[{"id": 12345, "name": "Intro to CS", "course_code": "CS101", "workflow_state": "available", "start_at": "...", "end_at": "..."}]
|
||||
```
|
||||
|
||||
**list_assignments** returns:
|
||||
```json
|
||||
[{"id": 67890, "name": "Homework 1", "due_at": "2025-02-15T23:59:00Z", "points_possible": 100, "submission_types": ["online_upload"], "html_url": "...", "description": "...", "course_id": 12345}]
|
||||
```
|
||||
|
||||
Note: Assignment descriptions are truncated to 500 characters. The `html_url` field links to the full assignment page in Canvas.
|
||||
|
||||
## API Reference (curl)
|
||||
|
||||
```bash
|
||||
# List courses
|
||||
curl -s -H "Authorization: Bearer $CANVAS_API_TOKEN" \
|
||||
"$CANVAS_BASE_URL/api/v1/courses?enrollment_state=active&per_page=10"
|
||||
|
||||
# List assignments for a course
|
||||
curl -s -H "Authorization: Bearer $CANVAS_API_TOKEN" \
|
||||
"$CANVAS_BASE_URL/api/v1/courses/COURSE_ID/assignments?per_page=10&order_by=due_at"
|
||||
```
|
||||
|
||||
Canvas uses `Link` headers for pagination. The Python script handles pagination automatically.
|
||||
|
||||
## Rules
|
||||
|
||||
- This skill is **read-only** — it only fetches data, never modifies courses or assignments
|
||||
- On first use, verify auth by running `$CANVAS list_courses` — if it fails with 401, guide the user through setup
|
||||
- Canvas rate-limits to ~700 requests per 10 minutes; check `X-Rate-Limit-Remaining` header if hitting limits
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Fix |
|
||||
|---------|-----|
|
||||
| 401 Unauthorized | Token invalid or expired — regenerate in Canvas Settings |
|
||||
| 403 Forbidden | Token lacks permission for this course |
|
||||
| Empty course list | Try `--enrollment-state active` or omit the flag to see all states |
|
||||
| Wrong institution | Verify `CANVAS_BASE_URL` matches the URL in your browser |
|
||||
| Timeout errors | Check network connectivity to your Canvas instance |
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
---
|
||||
title: "Decision Questionnaire — Turn an unanswerable decision into a questionnaire doc"
|
||||
sidebar_label: "Decision Questionnaire"
|
||||
description: "Turn an unanswerable decision into a questionnaire doc"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Decision Questionnaire
|
||||
|
||||
Turn an unanswerable decision into a questionnaire doc.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/productivity/decision-questionnaire` |
|
||||
| Path | `optional-skills/productivity\decision-questionnaire` |
|
||||
| Version | `1.0.0` |
|
||||
| Author | Matt Pocock (mattpocock/skills, to-questionnaire) + Hermes Agent |
|
||||
| License | MIT |
|
||||
| Platforms | linux, macos, windows |
|
||||
| Tags | `questionnaire`, `decision`, `async`, `stakeholder`, `discovery`, `communication` |
|
||||
| Related skills | [`meeting-action-items`](/docs/user-guide/skills/bundled/productivity/productivity-meeting-action-items), [`document-to-action-items`](/docs/user-guide/skills/bundled/productivity/productivity-document-to-action-items) |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# Decision Questionnaire
|
||||
|
||||
Turns something the user can't answer alone into a **questionnaire**: a
|
||||
Markdown document they hand to one person to fill in async, or fill out
|
||||
together in a meeting. The recipient holds knowledge the user lacks; the
|
||||
questionnaire pulls it out of them.
|
||||
|
||||
Ported from mattpocock/skills' MIT-licensed `to-questionnaire` skill.
|
||||
|
||||
## When to Use
|
||||
|
||||
- A decision blocks on facts or judgment held by someone else (a domain
|
||||
expert, a stakeholder, a vendor contact, ops)
|
||||
- The user says "I need to ask X about this" or keeps deferring a decision
|
||||
pending someone else's input
|
||||
- Preparing for a meeting where specific answers must come back
|
||||
|
||||
Do NOT use when the answer is discoverable from the environment (codebase,
|
||||
docs, web) — find it yourself first.
|
||||
|
||||
## Core Principle: Interview the Send, Not the Subject
|
||||
|
||||
The user cannot answer the subject-matter questions (that's the point), but
|
||||
they can ALWAYS answer questions about the send. Interview them only about
|
||||
that, in two short exchanges:
|
||||
|
||||
1. **Who is it going to?** Role, expertise, relationship to the user. This
|
||||
fixes the questionnaire's tone and how much context it must carry. Done
|
||||
when you know who the recipient is and what they know that the user
|
||||
doesn't.
|
||||
2. **What do you need back?** The specific decisions or facts the user
|
||||
can't resolve alone. Done when you have a concrete list of what the user
|
||||
must walk away able to do or decide.
|
||||
|
||||
Then **write the questionnaire**: draft questions aimed at the gap between
|
||||
what the recipient knows and what the user needs, following the structure
|
||||
below. Write it to `decision-questionnaire-<slug>.md` in the current
|
||||
directory (slug from the topic) and report the absolute path. Done when the
|
||||
file exists and every item from step 2 is covered by a question.
|
||||
|
||||
## Document Structure
|
||||
|
||||
Frame it as a **discovery questionnaire**: the user lacks context, the
|
||||
recipient holds it. Order questions most-important-first (async means you
|
||||
may only get one pass). Group under `##` headings by theme once there are
|
||||
more than a handful.
|
||||
|
||||
Template:
|
||||
|
||||
```markdown
|
||||
# <Questionnaire title>
|
||||
|
||||
**Purpose:** why this questionnaire exists and the decision riding on it.
|
||||
|
||||
**From:** <the user> · **To:** <the recipient> ·
|
||||
**How your answers will be used:** <where they go>
|
||||
|
||||
## Context
|
||||
|
||||
One paragraph orienting a recipient who wasn't in the user's head. Enough
|
||||
to answer well, not a page.
|
||||
|
||||
## How to answer
|
||||
|
||||
Deadline and rough effort. Partial answers and "I don't know" are useful:
|
||||
flag anything you're unsure of rather than skipping it.
|
||||
|
||||
## <Theme heading>
|
||||
|
||||
### <One question — a single idea, never compound>
|
||||
|
||||
_Why this matters: <one line, only where the question could be misread or
|
||||
invite a throwaway answer>._
|
||||
|
||||
>
|
||||
|
||||
## Anything else?
|
||||
|
||||
A closing catch-all: anything we didn't ask that we should know?
|
||||
```
|
||||
|
||||
Every question gets an answer stub (`>`) directly beneath it.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
1. **Grilling the user about the subject.** They can't answer it — that's
|
||||
why the document exists. Only interview the send.
|
||||
2. **Compound questions.** One idea per question; split "and/or" questions.
|
||||
3. **Burying the critical question.** Most-important-first; async
|
||||
recipients fade.
|
||||
4. **Context dump.** One orienting paragraph, not the whole history.
|
||||
5. **Skipping the "why this matters" line on ambiguous questions.** It's
|
||||
what turns a throwaway answer into a useful one — but don't add it to
|
||||
questions that are already unambiguous.
|
||||
|
||||
## Verification
|
||||
|
||||
- [ ] Recipient's role/knowledge and the needed outcomes captured in two
|
||||
exchanges before drafting
|
||||
- [ ] Every step-2 item covered by at least one question
|
||||
- [ ] Questions single-idea, most-important-first, answer stubs present
|
||||
- [ ] File written and absolute path reported to the user
|
||||
@@ -0,0 +1,231 @@
|
||||
---
|
||||
title: "Here Now — Publish sites to {slug}.here.now and store files in Drives"
|
||||
sidebar_label: "Here Now"
|
||||
description: "Publish sites to {slug}.here.now and store files in Drives"
|
||||
---
|
||||
|
||||
{/* This page is auto-generated from the skill's SKILL.md by website/scripts/generate-skill-docs.py. Edit the source SKILL.md, not this page. */}
|
||||
|
||||
# Here Now
|
||||
|
||||
Publish sites to {slug}.here.now and store files in Drives.
|
||||
|
||||
## Skill metadata
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Source | Optional — install with `hermes skills install official/productivity/here-now` |
|
||||
| Path | `optional-skills/productivity\here-now` |
|
||||
| Version | `1.15.3` |
|
||||
| Author | here.now |
|
||||
| License | MIT |
|
||||
| Platforms | macos, linux |
|
||||
| Tags | `here.now`, `herenow`, `publish`, `deploy`, `hosting`, `static-site`, `web`, `share`, `URL`, `drive`, `storage` |
|
||||
|
||||
## Reference: full SKILL.md
|
||||
|
||||
:::info
|
||||
The following is the complete skill definition that Hermes loads when this skill is triggered. This is what the agent sees as instructions when the skill is active.
|
||||
:::
|
||||
|
||||
# here.now
|
||||
|
||||
here.now lets agents publish websites and store private files in cloud Drives.
|
||||
|
||||
Use here.now for two jobs:
|
||||
|
||||
- **Sites**: publish websites and files at `{slug}.here.now`.
|
||||
- **Drives**: store private agent files in cloud folders.
|
||||
|
||||
## Current docs
|
||||
|
||||
**Before answering questions about here.now capabilities, features, or workflows, read the current docs:**
|
||||
|
||||
→ **https://here.now/docs**
|
||||
|
||||
Read the docs:
|
||||
|
||||
- at the first here.now-related interaction in a conversation
|
||||
- any time the user asks how to do something
|
||||
- any time the user asks what is possible, supported, or recommended
|
||||
- before telling the user a feature is unsupported
|
||||
|
||||
Topics that require current docs (do not rely on local skill text alone):
|
||||
|
||||
- Drives and Drive sharing
|
||||
- custom domains
|
||||
- payments and payment gating
|
||||
- forking
|
||||
- proxy routes and service variables
|
||||
- handles and links
|
||||
- limits and quotas
|
||||
- SPA routing
|
||||
- error handling and remediation
|
||||
- feature availability
|
||||
|
||||
**If docs and live API behavior disagree, trust the live API behavior.**
|
||||
|
||||
If the docs fetch fails or times out, continue with the local skill and live API/script output. Prefer live API behavior for active operations.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Required binaries: `curl`, `file`, `jq`
|
||||
- Optional environment variable: `$HERENOW_API_KEY`
|
||||
- Optional Drive token variable: `$HERENOW_DRIVE_TOKEN`
|
||||
- Optional credentials file: `~/.herenow/credentials`
|
||||
- Skill helper paths:
|
||||
- `${HERMES_SKILL_DIR}/scripts/publish.sh` for publishing sites
|
||||
- `${HERMES_SKILL_DIR}/scripts/drive.sh` for private Drive storage
|
||||
|
||||
## Create a site
|
||||
|
||||
```bash
|
||||
PUBLISH="${HERMES_SKILL_DIR}/scripts/publish.sh"
|
||||
bash "$PUBLISH" {file-or-dir} --client hermes
|
||||
```
|
||||
|
||||
Outputs the live URL (e.g. `https://bright-canvas-a7k2.here.now/`).
|
||||
|
||||
Under the hood this is a three-step flow: create/update -> upload files -> finalize. A site is not live until finalize succeeds.
|
||||
|
||||
Without an API key this creates an **anonymous site** that expires in 24 hours.
|
||||
With a saved API key, the site is permanent.
|
||||
|
||||
**File structure:** For HTML sites, place `index.html` at the root of the directory you publish, not inside a subdirectory. The directory's contents become the site root. For example, publish `my-site/` where `my-site/index.html` exists — don't publish a parent folder that contains `my-site/`.
|
||||
|
||||
You can also publish raw files without any HTML. Single files get a rich auto-viewer (images, PDF, video, audio). Multiple files get an auto-generated directory listing with folder navigation and an image gallery.
|
||||
|
||||
## Update an existing site
|
||||
|
||||
```bash
|
||||
PUBLISH="${HERMES_SKILL_DIR}/scripts/publish.sh"
|
||||
bash "$PUBLISH" {file-or-dir} --slug {slug} --client hermes
|
||||
```
|
||||
|
||||
The script auto-loads the `claimToken` from `.herenow/state.json` when updating anonymous sites. Pass `--claim-token {token}` to override.
|
||||
|
||||
Authenticated updates require a saved API key.
|
||||
|
||||
## Use a Drive
|
||||
|
||||
Use a Drive when the user wants private cloud storage for agent files: documents, context, memory, plans, assets, media, research, code, and anything else that should persist without being published as a website.
|
||||
|
||||
Every signed-in account has a default Drive named `My Drive`.
|
||||
|
||||
```bash
|
||||
DRIVE="${HERMES_SKILL_DIR}/scripts/drive.sh"
|
||||
bash "$DRIVE" default
|
||||
bash "$DRIVE" ls "My Drive"
|
||||
bash "$DRIVE" put "My Drive" notes/today.md --from ./notes/today.md
|
||||
bash "$DRIVE" cat "My Drive" notes/today.md
|
||||
bash "$DRIVE" share "My Drive" --perms write --prefix notes/ --ttl 7d
|
||||
```
|
||||
|
||||
Use scoped Drive tokens for agent-to-agent handoff. If you receive a `herenow_drive` share block, use its `token` as `Authorization: Bearer <token>` against `api_base`, respect `pathPrefix` when present, and preserve ETags on writes. A `pathPrefix` of `null` means full-Drive access. If the skill is available, prefer `drive.sh`; otherwise call the listed API operations directly.
|
||||
|
||||
## API key storage
|
||||
|
||||
The publish script reads the API key from these sources (first match wins):
|
||||
|
||||
1. `--api-key {key}` flag (CI/scripting only — avoid in interactive use)
|
||||
2. `$HERENOW_API_KEY` environment variable
|
||||
3. `~/.herenow/credentials` file (recommended for agents)
|
||||
|
||||
To store a key, write it to the credentials file:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.herenow && echo "{API_KEY}" > ~/.herenow/credentials && chmod 600 ~/.herenow/credentials
|
||||
```
|
||||
|
||||
**IMPORTANT**: After receiving an API key, save it immediately — run the command above yourself. Do not ask the user to run it manually. Avoid passing the key via CLI flags (e.g. `--api-key`) in interactive sessions; the credentials file is the preferred storage method.
|
||||
|
||||
Never commit credentials or local state files (`~/.herenow/credentials`, `.herenow/state.json`) to source control.
|
||||
|
||||
## Getting an API key
|
||||
|
||||
To upgrade from anonymous (24h) to permanent sites:
|
||||
|
||||
1. Ask the user for their email address.
|
||||
2. Request a one-time sign-in code:
|
||||
|
||||
```bash
|
||||
curl -sS https://here.now/api/auth/agent/request-code \
|
||||
-H "content-type: application/json" \
|
||||
-d '{"email": "user@example.com"}'
|
||||
```
|
||||
|
||||
3. Tell the user: "Check your inbox for a sign-in code from here.now and paste it here."
|
||||
4. Verify the code and get the API key:
|
||||
|
||||
```bash
|
||||
curl -sS https://here.now/api/auth/agent/verify-code \
|
||||
-H "content-type: application/json" \
|
||||
-d '{"email":"user@example.com","code":"ABCD-2345"}'
|
||||
```
|
||||
|
||||
5. Save the returned `apiKey` yourself (do not ask the user to do this):
|
||||
|
||||
```bash
|
||||
mkdir -p ~/.herenow && echo "{API_KEY}" > ~/.herenow/credentials && chmod 600 ~/.herenow/credentials
|
||||
```
|
||||
|
||||
## State file
|
||||
|
||||
After every site create/update, the script writes to `.herenow/state.json` in the working directory:
|
||||
|
||||
```json
|
||||
{
|
||||
"publishes": {
|
||||
"bright-canvas-a7k2": {
|
||||
"siteUrl": "https://bright-canvas-a7k2.here.now/",
|
||||
"claimToken": "abc123",
|
||||
"claimUrl": "https://here.now/claim?slug=bright-canvas-a7k2&token=abc123",
|
||||
"expiresAt": "2026-02-18T01:00:00.000Z"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Before creating or updating sites, you may check this file to find prior slugs.
|
||||
Treat `.herenow/state.json` as internal cache only.
|
||||
Never present this local file path as a URL, and never use it as source of truth for auth mode, expiry, or claim URL.
|
||||
|
||||
## What to tell the user
|
||||
|
||||
For published sites:
|
||||
|
||||
- Always share the `siteUrl` from the current script run.
|
||||
- Read and follow `publish_result.*` lines from script stderr to determine auth mode.
|
||||
- When `publish_result.auth_mode=authenticated`: tell the user the site is **permanent** and saved to their account. No claim URL is needed.
|
||||
- When `publish_result.auth_mode=anonymous`: tell the user the site **expires in 24 hours**. Share the claim URL (if `publish_result.claim_url` is non-empty and starts with `https://`) so they can keep it permanently. Warn that claim tokens are only returned once and cannot be recovered.
|
||||
- Never tell the user to inspect `.herenow/state.json` for claim URLs or auth status.
|
||||
|
||||
For Drives:
|
||||
|
||||
- Do not describe Drive files as public URLs.
|
||||
- Tell the user Drive contents are private unless shared with a scoped token.
|
||||
- When sharing access with another agent, prefer a scoped token with a narrow `pathPrefix` and short TTL.
|
||||
|
||||
## publish.sh options
|
||||
|
||||
| Flag | Description |
|
||||
| ---------------------- | -------------------------------------------- |
|
||||
| `--slug {slug}` | Update an existing site instead of creating |
|
||||
| `--claim-token {token}`| Override claim token for anonymous updates |
|
||||
| `--title {text}` | Viewer title (non-HTML sites) |
|
||||
| `--description {text}` | Viewer description |
|
||||
| `--ttl {seconds}` | Set expiry (authenticated only) |
|
||||
| `--client {name}` | Agent name for attribution (e.g. `hermes`) |
|
||||
| `--base-url {url}` | API base URL (default: `https://here.now`) |
|
||||
| `--allow-nonherenow-base-url` | Allow sending auth to non-default `--base-url` |
|
||||
| `--api-key {key}` | API key override (prefer credentials file) |
|
||||
| `--spa` | Enable SPA routing (serve index.html for unknown paths) |
|
||||
| `--forkable` | Allow others to fork this site |
|
||||
|
||||
## Beyond publish.sh
|
||||
|
||||
For Drive operations, use `drive.sh` or the Drive API. For broader account and site management — delete, metadata, passwords, payments, domains, handles, links, variables, proxy routes, forking, duplication, and more — see the current docs:
|
||||
|
||||
→ **https://here.now/docs**
|
||||
|
||||
Full docs: https://here.now/docs
|
||||
Loaded 100 of 11340 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user