Ethan — Lightweight personal AI agent with memory, skills, and multi-model support
pip install ethan-agent==0.5.338 Copy PIP instructions
A lightweight, extensible personal AI agent built in Python. Designed to run persistently on your own hardware with memory that grows over time, scheduled tasks, and a pluggable tool/skill system.
Ethan combines ideas from OpenClaw (structured agent loop, layered memory), Hermes Agent (self-improving skills, memory consolidation), and nanobot (minimal core, readable codebase).
Companion mode — 苏念 (Surrender Experiment counselor) (built-in skill, no install needed)
Legal expert mode — legal-assistant (install on demand)
Feature installation matrix — what works out of the box vs. what needs an extra install step:
pip3 install ethan-agent Set an API key and start:
# Any OpenAI-compatible API (OpenAI / Gemini / OpenRouter / DeepSeek / Ollama / etc.) ethan provider set openai_compat --api-key sk-xxx --base-url https://api.openai.com/v1 ethan model default gpt-5.4 # or gemini-2.5-flash, etc. # OR Anthropic Claude ethan provider set anthropic --api-key sk-ant-xxx # OR Zhipu GLM (built-in preset — fills base_url/type/anti-cache + registers glm-5.2 etc.) ethan provider set glm --api-key ethan model default glm-5.2 # (see `ethan provider presets` for all built-in presets) ethan 💡 First-run wizard: if you just run ethan without configuring a provider first, an interactive prompt will guide you through choosing a provider (default: OpenAI-compatible), entering Base URL, then API Key, and finally a default model ID.
⚠️ Already running? If ethan serve, the desktop app, or ethan web is already up, restart it after any ethan provider set / ethan model default change. The running server caches config in memory and won't pick up edits to ~/.ethan/config.yaml until it restarts.
💡 Notice: Run ethan command to start the interactive chat REPL in your terminal. When ethan serve is running, it also hosts the Web UI on port 8900. Running ethan will automatically open it in your browser. You can also run ethan web to open the Web UI directly.
That's it. On first run, default skills and system files are written to ~/.ethan/.
Prefer a native app over the browser? Download the desktop client from GitHub Releases:
The desktop app bundles the Web UI in a native window — just point it at your ethan serve instance (local or remote) and log in with your token.
Single container with API + Web UI on the same port (8900), data persisted to the host's ~/.ethan/ via bind mount (inspectable, backup-friendly, and shared with any pip-installed ethan on the same machine). A bundled SearXNG container provides web search. No need to clone the repository.
mkdir ethan-agent && cd ethan-agent # Self-contained variant: pulls the published image (no code clone needed) curl -o docker-compose.yml https://raw.githubusercontent.com/llm011/ethan-agent/main/deploy/docker-compose.yml curl -o .env.example https://raw.githubusercontent.com/llm011/ethan-agent/main/deploy/.env.example # (Optional) SearXNG settings file mkdir -p searxng && curl -o searxng/settings.yml https://raw.githubusercontent.com/llm011/ethan-agent/main/deploy/searxng/settings.yml 2. Configure Copy .env.example to .env and fill in your API keys (at least one provider):
cp .env.example .env # Edit .env — set ANTHROPIC_API_KEY or OPENAI_API_KEY + OPENAI_BASE_URL 💡 Tip: you can also skip the .env and configure the provider interactively inside the container — see step 4.
docker compose up -d docker compose logs -f ethan # the startup log prints the 🔑 Web UI Token 4. Get the Web UI token The startup log prints the token, but if you missed it, either:
# Recommended first-run path: enter the TUI inside the container. # This prints the token, and if no provider is configured yet it launches # the interactive onboarding wizard (choose provider → base_url → api_key → default model). docker exec -it ethan-agent ethan Or just fetch the token directly:
docker exec -it ethan-agent ethan web token # or read it from the mounted config file grep auth_token ~/.ethan/config.yaml 5. Access Web UI: http://localhost:8900 (log in with the token from step 4) API: http://localhost:8900 Health check: http://localhost:8900/health SearXNG (web search): http://localhost:8888 6. Common commands docker compose logs -f ethan # tail logs docker compose restart ethan # restart service docker compose pull && docker compose up -d # update to latest version docker compose down # stop One-shot legal expert mode: set ETHAN_INSTALL_SKILLS=legal before docker compose up (or run docker compose exec ethan-agent ethan skill add legal after the container is up) to install the legal-assistant skill; then pick "⚖️ 法律专家" in the Web mode dropdown to activate it.
Ethan supports multiple isolated users sharing one instance. Each user has their own memory (structured memories / procedures / sessions), skills, and knowledge base — fully isolated per user. System prompts and provider config stay shared.
Define users in config.yaml (each user binds a web_token for browser login and api_keys for the /v1/chat/completions API — both resolve to the same user_id):
users: - id: admin # stable identifier, also the data dir name (use ASCII) name: Admin web_token: admin_pass # browser login api_keys: [sk-ethan-admin-key] # programmatic API access is_admin: true - id: alice name: Alice web_token: alice_pass api_keys: [sk-ethan-alice-key] is_admin: false If users is empty (or absent), Ethan auto-creates an admin user whose web_token reuses network.auth_token — so existing single-user deployments keep working with zero config change. On first launch, existing global data is migrated to the admin user's directory (originals kept as backup; idempotent).
# From PyPI pip install ethan-agent # Or from source git clone https://github.com/llm011/ethan-agent.git cd ethan-agent uv sync Semantic Router (smarter skill matching — built-in) By default, Ethan uses keyword matching to decide which skill to activate. On top of that, a built-in semantic router (BGE INT8 + LR head) adds recall so differently-phrased requests still match (e.g. triggering the Feishu skill by saying "pass a message to the client" instead of literally "send Feishu").
The deps (onnxruntime / tokenizers / numpy) ship with pip install ethan-agent — no extra install step. The BGE model (~24MB) auto-downloads on first use and is cached locally:
# Pre-fetch the model (optional — the first message auto-downloads it anyway) ethan router pull # Check status ethan router status # "✓ router ready" means you're set Graceful fallback: if the model isn't downloaded yet or you're offline, it silently falls back to keyword matching — nothing breaks. The model is hosted on GitHub, downloaded and cached locally on first use, then works offline. Configure ethan provider set anthropic --api-key sk-ant-xxx # or ethan provider set openai_compat --api-key sk-xxx --base-url https://api.example.com/v1 ⚠️ Restart any running ethan serve / desktop app / ethan web after changing provider or model config — the server caches config in memory and only reloads on restart.
# Interactive REPL ethan # Launch Web UI and open in browser ethan web # (Supports custom port via `--port 8900` or direct URL via `--url`) # Manage Web UI login token ethan web token ethan web token --rotate # Single-turn query ethan -p "What's the weather in Tokyo?" # Specify model ethan -m claude-sonnet-4-6 # Resume last session ethan -r last # Start HTTP API server (needed for Web UI) ethan serve Web UI (dev mode) cd web npm install npm run dev # http://localhost:3000 (dev mode, API still on port 8900) Android App Native mobile client in app/android/. Requires Android SDK 35 and JDK 17+.
cd app/android ./gradlew assembleDebug # APK: app/build/outputs/apk/debug/app-debug.apk On first launch, configure the server URL (e.g. http:// :8900) and Access Token (network.auth_token in ~/.ethan/config.yaml). See app/android/PRD.md for the full feature list.
./deploy/install.sh # or use the built-in commands: ethan server install # install + start ethan server status # check status (also flags multi-instance conflicts) ethan server restart # restart ethan server stop # stop ethan server uninstall # uninstall ⚠️ Only one ethan instance may run at a time. The real conflict is which process holds sessions.db open — not the port. sessions.db uses DELETE journal mode, whose write lock is whole-database exclusive, so two instances on different ports still deadlock each other. Symptoms: log spam of database is locked; worst case a write transaction stalls, sessions.db-journal never gets released, and even a plain SELECT returns database is locked — which users see as "opening a conversation hangs forever."
A duplicate start is now rejected immediately (exit code 1) in either case: the port already has a healthy instance, or another instance (even on a different port) has the same sessions.db open. Bypass with ETHAN_NO_WATCHDOG=1 in dev/test (worktree tests share the live DB), or ethan serve --force when you really mean it (not recommended — it really will lock-conflict).
ETHAN_NO_WATCHDOG only accepts 1; =0 does not disable it.
If the server won't start or keeps dropping, check: ethan server status, lsof -p | grep sessions.db, ls -la ~/.ethan/db/sessions.db-journal (present and long-lived = a stalled write transaction), cat /tmp/ethan/watchdog.log, and tail -f ~/.ethan/logs/api.err.log.
The watchdog also retires itself: a non-launchd start leaves behind a detached watchdog that only knows a port, not its owner. If the serve that spawned it is gone (e.g. replaced by a launchd-managed instance on another port), the watchdog would otherwise keep resurrecting ghost instances on the stale port forever. The retry budget now depends on how the watchdog started:
Real crashes are still restarted by the outer supervisor (launchd KeepAlive / manual ethan serve).
Note: launchd's default maxfiles is only 256, which is low for ethan (Lark listeners + WeChat polling + browser WebSockets + several SQLite connections). Exhausting it raises Errno 24: Too many open files, which can land on the SQLite commit path and stall a write transaction. The plist template now sets SoftResourceLimits/HardResourceLimits to 65536.
ethan/ ├── core/ │ ├── agent.py # ReAct loop, two-track router (fast/full) │ ├── config.py # YAML config (~/.ethan/config.yaml) │ └── heartbeat.py # Heartbeat system, periodic maintenance ├── providers/ │ ├── base.py # Unified interface (Message, ToolCall, BaseProvider) │ ├── anthropic.py # Claude native protocol + Prompt Caching │ ├── openai_compat.py # OpenAI-compatible protocol │ └── manager.py # Route model ID → provider ├── memory/ │ ├── session.py # Session persistence (SQLite) │ ├── working.py # Three-tier sliding window memory │ ├── store.py # Structured memory store (memories/evidence/candidates/jobs/FTS) │ ├── extractors.py # LLM candidate extraction (quote-backed) │ ├── admission.py # Deterministic admission + semantic pairing │ ├── dimensions.py # Dimension registry (whitelist + prompt generation) │ ├── recall.py # Hybrid recall (FTS + vector, RRF) │ ├── memory_vectors.py # BGE vector index for memories │ ├── nightly_consolidation.py # Unified nightly pass (structured + dream) │ ├── procedures.py # Behavioral rules (learned from corrections) │ └── consolidator.py # Compress with cheap model ├── skills/ │ ├── loader.py # Load skills (directory format + legacy .md) │ ├── registry.py # Match (with channel filter) + hit stats │ ├── stats.py # Hit count + correction collection │ ├── updater.py # Auto-update skill content via cheap model │ └── generator.py # Auto-generate skills from sessions ├── tools/ │ ├── base.py # BaseTool abstract class │ ├── registry.py # Registry + concurrent executor + turn cache │ ├── result_compressor.py # Auto-summarize long tool output │ └── builtin/ │ ├── shell.py # Execute shell commands │ ├── web_search.py # DuckDuckGo search │ ├── web.py # Fetch & extract web page text │ ├── file.py # File read/write/list │ ├── memory_write.py # Proactive fact write │ ├── procedure_write.py # Proactive procedure write │ ├── profile_update.py # Update user profile │ ├── skill_create.py # Create skill mid-conversation │ └── lark_tools.py # Lark CLI wrappers (calendar / chat messages / message send) ├── scheduler/ │ └── cron.py # APScheduler with SQLite persistence └── interface/ ├── cli.py # Typer CLI entry point ├── repl.py # Interactive REPL with prompt_toolkit ├── api.py # FastAPI HTTP + SSE streaming ├── lark_events.py # Lark WebSocket └── commands/ # Subcommands (model, provider, session, skill, schedule) Memory System Ethan's long-term memory is a structured pipeline (extract → admit → recall → nightly consolidation) with several satellite stores:
Short sessions (<3 turns) extract immediately, then incrementally every 3 turns on the main chat model; in-session compression is batched (not per-turn) and uses an automatically inferred cheap model (e.g. Haiku for Claude users, Flash Lite for Gemini users).
Agent proactively writes to all layers mid-conversation via memory_write, procedure_write, and profile_update tools — no waiting for the next compression cycle.
Skills are Markdown files loaded from ~/.ethan/skills/. On first run, default skills (channels, deepwiki, lark-im, lark-shared, skills-manager, article-to-video, use-browser, agent-browser, dev-browser, tab-declutter, …) are automatically copied there from the package.
Both directory format ( /SKILL.md + references/) and legacy single-file .md format are supported. When a directory-format skill is matched, its references/*.md filenames plus a one-line summary are listed in the injected context so the model knows which detail docs exist — use skill_read(name=..., file="references/ .md") to pull the full content on demand (pull-based, not bulk-injected).
--- name: deploy-checklist trigger: deploy|ship|release description: Pre-deployment checklist fast_path: true # route to fast track when triggered channels: # empty = all channels; list = restrict - web version: "1.0" --- Steps before deploying: 1. Run tests 2. Check for uncommitted changes 3. ... When a user message matches a skill's trigger, the skill content is injected into the system prompt. Built-in skills include channels, lark-im, home-assistant, and article-to-video.
Skills accumulate hit stats and user corrections. When corrections reach a threshold (default: 2), the Heartbeat job merges them into the skill file using a cheap model.
The built-in article-to-video skill turns a topic, article body, local Markdown/TXT file, or public URL into an MP4. The model creates the structured script and storyboard; Edge TTS generates per-scene narration and captions; Open Motion renders code-generated motion graphics against the measured audio timeline. Domain-aware visuals are supported: the finance domain adds candlestick charts with Bollinger bands and markers, yellow keyword callouts, and a reusable virtual-presenter sprite pack (images are produced with GPT image 2 from the shipped prompt pack, then imported into ~/.ethan/assets/library/). Web and Desktop file cards can play or download the finished video, while production files are delivered separately. edge-tts, Playwright (for Open Motion rendering), and FFmpeg install lazily and do not enter Ethan's core Python dependencies.
Tools are pluggable — add a new one without touching the agent loop:
from ethan.tools.base import BaseTool class MyTool(BaseTool): name = "my_tool" description = "Does something useful" fast_path = False # set True to make available in fast-track mode cacheable = False # set True to cache identical calls within a turn no_compress = False # set True if output carries IDs/refs/structured data the model must reuse verbatim parameters = {"type": "object", "properties": {...}, "required": [...]} async def run(self, **kwargs) -> str: return "result" Register it in cli.py and the LLM will automatically use it when relevant.
no_compress: tool output over 4000 chars is auto-summarized by a cheap model before reaching the main model. Leave it off when the output is prose to read (web pages, logs). Turn it on when the output contains data the model must pass back verbatim — IDs, refs, paths, structured JSON — otherwise the summary loses those tokens and the model can't act on the result.
Built-in tools also include ui_card, which renders structured info as cards instead of plain text. High-frequency types (comparison / ranking / stats / timeline) use fixed backend templates — the model just fills in typed data, so styling stays clean and consistent; free-form cards can still be hand-authored. Rendering is channel-aware over the same structured card data: the web renders A2UI via @a2ui/react, the REPL degrades to text, and Feishu/Lark renders native interactive cards (an incremental nicety on top of the base text/post + streaming-card output). Format details live in the on-demand ui-card skill, so the system prompt stays lean.
The generate_chart tool renders interactive Chart.js charts (bar / line / pie / doughnut / horizontalBar / radar) in the web UI, following the MCP Apps UI-resource convention (SEP-1865):
Charts persist on the assistant message (mcp_apps column), so they re-render after a page refresh.
ethan Start interactive REPL ethan -p "..." Single-turn query ethan -m MODEL Use specific model ethan -r last Resume last session ethan serve Start HTTP API server (foreground) ethan serve stop Stop background serve process ethan serve restart Restart background serve process ethan model list|add|remove|default ethan provider list|set ethan session list|show|delete ethan skill list|show|add|create ethan schedule list|remove|pause|resume ethan trust add|list|remove Trusted dirs (skip write-consent prompts) HTTP API GET /health # Health check GET /models # Available models POST /chat # Chat (stream: true for SSE) GET /sessions # Session list GET /sessions/{id} # Session detail + messages GET /memory/facts # Memories list, paged (limit/offset/total) GET /memory/records # Structured memories, paged (filter: type/domain/status) GET /memory/records/{id} # Memory detail + evidence chain GET /skills # Skill list POST /skills # Create skill POST /skills/evolve # Trigger skill auto-update GET /schedule # Scheduled jobs GET /system-prompt-preview # Current system prompt preview GET /channels # Channel list GET /knowledge/search # Semantic search GET /ui-resources # MCP Apps UI resources (SEP-1865): list GET /ui-resources/read?uri= # MCP Apps UI resource: read HTML + _meta GET /sessions/{id} returns the whole message history, so its payload size is what decides how fast a session opens. Image cards carry a relative asset path (assets/images/...) rather than inline base64 data URIs; a startup migration converts any pre-existing inline cards to asset files.
providers: anthropic: api_key: sk-ant-xxx base_url: https://api.anthropic.com # optional proxy: null # per-provider proxy openai_compat: api_key: sk-xxx base_url: https://api.openai.com/v1 models: - id: claude-sonnet-4-6 provider: anthropic description: Claude Sonnet 4.6 alias: [sonnet] - id: gpt-4o provider: openai_compat alias: [gpt] network: proxy: http://127.0.0.1:7890 # global proxy server: # `ethan serve` (HTTP API + Web UI) listen address host: 0.0.0.0 # set 127.0.0.1 for local-only access port: 8900 # explicit `--port` still wins; restart serve after changing defaults: model: claude-sonnet-4-6 agent_name: Ethan max_tokens: 4096 max_tool_iterations: 10 routing: fast_rules: - name: Home automation keywords: ["turn off*light", "play music"] tools: ["shell"] skills: ["home-assistant-control"] Environment variables in .env override config values (useful for secrets).
~/.ethan/ ├── config.yaml # Main config (providers, models, routing) ├── system/ │ ├── identity.md # Agent identity (name, role) │ ├── soul.md # Behavioral principles │ ├── naming.md # Conversation naming rules (injected into title prompt) │ └── heartbeat.md # Heartbeat tasks (natural language) ├── memory/ │ ├── memory.db # Structured memories + evidence + insights + vector index │ ├── playbook.json # Behavioral rules │ └── user_profile.md # User profile (narrative) ├── skills/ # User-defined skills │ └── / │ └── SKILL.md └── sessions.db # Session history (SQLite) Feature checklist Tool calls # 1. Web search Send: "What's the CNY/USD exchange rate today?" Verify: the tool timeline shows web_search # 2. Shell execution Send: "List the files in the current directory" Verify: the shell tool runs and returns the file list # 3. Tool result compression (needs a large output) Send: "Run find / -name '*.log' 2>/dev/null | head -100" Verify: the reply starts with a [summary, N chars of raw output] prefix Routing & caching # 1. Fast path speed Send: "turn off the light" (or any word in fast_keywords) Check the TTFT reading in the REPL status bar or Web UI — should be 0, the cache was hit # 3. Session open speed Ask the agent to read a local image, then click back into that session In DevTools Network, GET /sessions/{id} should be a few hundred KB (not MB) Card images should load from assets/images/, not start with data:image/png;base64 # 4. Long-session paging Open a session with a few hundred messages and watch the first-screen request, GET /sessions/{id}?limit=30 — the body should hold only the latest 30 messages (a few hundred KB). Scrolling up fires another request with before= , and once you reach the start (first user message) it stops: has_more=false Roadmap ✅ Completed Core Agent
Full documentation is available at llm011.github.io/ethan-agent — the same docs site you see in Ethan's built-in "Docs" tab.
All source markdown lives in docs/; changes to main auto-deploy via GitHub Actions.
agent ai assistant claude gemini llm memory skills
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.




