{"id":49543891,"url":"https://github.com/hsaghir/looplet","last_synced_at":"2026-05-02T17:04:49.385Z","repository":{"id":353011902,"uuid":"1214179954","full_name":"hsaghir/looplet","owner":"hsaghir","description":"The tool-calling loop for LLM agents; iterator-first, protocol-hooked, one dependency.","archived":false,"fork":false,"pushed_at":"2026-04-30T06:38:01.000Z","size":1619,"stargazers_count":5,"open_issues_count":9,"forks_count":2,"subscribers_count":0,"default_branch":"master","last_synced_at":"2026-04-30T08:15:49.923Z","etag":null,"topics":["agent-framework","agents","ai-agents","anthropic","asyncio","composable","function-calling","hooks","llm","llm-agent","mcp","observability","ollama","openai","protocol","python","tool-calling","tool-use"],"latest_commit_sha":null,"homepage":"https://hsaghir.github.io/looplet/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hsaghir.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":"ROADMAP.md","authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2026-04-18T08:13:15.000Z","updated_at":"2026-04-30T06:38:03.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/hsaghir/looplet","commit_stats":null,"previous_names":["hsaghir/looplet"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/hsaghir/looplet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hsaghir%2Flooplet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hsaghir%2Flooplet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hsaghir%2Flooplet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hsaghir%2Flooplet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hsaghir","download_url":"https://codeload.github.com/hsaghir/looplet/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hsaghir%2Flooplet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32542202,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-02T12:25:33.646Z","status":"ssl_error","status_checked_at":"2026-05-02T12:24:51.733Z","response_time":132,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent-framework","agents","ai-agents","anthropic","asyncio","composable","function-calling","hooks","llm","llm-agent","mcp","observability","ollama","openai","protocol","python","tool-calling","tool-use"],"created_at":"2026-05-02T17:04:47.990Z","updated_at":"2026-05-02T17:04:49.370Z","avatar_url":"https://github.com/hsaghir.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# looplet\n\n![demo — 4-tool data-cleanup loop with a DebugHook trace and a human approval pause](docs/demo.gif)\n\n[![CI](https://github.com/hsaghir/looplet/actions/workflows/ci.yml/badge.svg)](https://github.com/hsaghir/looplet/actions/workflows/ci.yml)\n[![codecov](https://codecov.io/gh/hsaghir/looplet/branch/master/graph/badge.svg)](https://codecov.io/gh/hsaghir/looplet)\n[![PyPI version](https://img.shields.io/pypi/v/looplet.svg)](https://pypi.org/project/looplet/)\n[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)\n[![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)\n[![Status: Beta](https://img.shields.io/badge/status-beta-orange.svg)](ROADMAP.md)\n\n**looplet exposes the agent loop as an iterator, makes every step observable, and lets you compose behavior with hooks.**\nBuild LLM agents that call tools in a loop while you keep ordinary\nPython control over every step — no graph DSL, no subclassing, no\nvendor lock-in. **Zero runtime dependencies.**\n\n\u003e Elevator pitch: looplet is the tiny agent loop you can actually own.\n\u003e Yield every tool call, inspect every result, intercept any decision,\n\u003e and grow from a 30-line prototype to a production agent without\n\u003e switching frameworks.\n\n```python\nfrom looplet import composable_loop\n\nfor step in composable_loop(llm=llm, tools=tools, task=task, config=cfg, state=state):\n    print(step.pretty())          # → \"#1 ✓ search(query='…') → 12 items [182ms]\"\n    if step.tool_result.error:\n        break                     # your loop, your control flow\n```\n\n```bash\npip install looplet               # core — zero third-party packages pulled in\npip install \"looplet[openai]\"     # works with OpenAI, Ollama, Together, Groq, vLLM, …\npip install \"looplet[anthropic]\"  # or Anthropic directly\n```\n\n---\n\n## The simple story\n\nEvery looplet agent turn is the same small mechanism:\n\n1. The LLM proposes a tool call.\n2. The registry validates and dispatches it.\n3. Hooks observe or steer the turn.\n4. State records the step.\n5. The loop yields a `Step` back to your `for` loop.\n\nThat is the whole mental model. Presets, skills, bundles, provenance,\nnative tool calling, and evals are useful layers around this mechanism;\nthey do not replace it.\n\n```python\nfor step in composable_loop(llm=llm, tools=tools, state=state, config=config, hooks=hooks):\n  print(step.pretty())\n```\n\nStart with ordinary Python code when you want full control. Start with a\nbundle when you want to run or share a packaged capability:\n\n```bash\npython -m looplet run ./skills/coder \"Fix the tests\" --workspace .\npython -m looplet blueprint ./skills/coder --workspace .\npython -m looplet export-code ./skills/coder coder_agent.py\n```\n\n---\n\n## Why it exists\n\nMost agent frameworks give you `agent.run(task)` and a black box. When the\nagent does something wrong at step 7, you can't step in between step 6 and\nstep 8. You end up forking the library or writing a second agent to babysit\nthe first.\n\n`looplet` does the opposite: **the loop is the product, and hooks are the\nextension API.** Every tool call is a `Step` object you can print, save,\nor diff. Every decision the loop makes — what goes in the next prompt,\nwhether to compact context, whether to dispatch a dangerous tool, whether\nto stop — is a `Protocol` method you implement in a few lines. Hooks\ncompose without inheritance. Nothing is hidden.\n\nThat one design choice is where the library's three practical superpowers\ncome from:\n\n* **Shape agent behaviour** without forking — a 10-line hook can redact PII\n  from every prompt, inject retrieved docs, rewrite tool arguments, or\n  rate-limit calls to a single tool. Hooks are the extension point the\n  framework *can't* close off because the loop itself is built on them.\n* **Manage context on your terms** — `compact_chain(Prune, Summarize,\n  Truncate)` is three hooks you wire together. Swap the strategy, change\n  the budget, fire on a different threshold — no monkey-patching.\n* **Debug and eval without a second tool** — `step.pretty()` is a\n  human-readable trace, `ProvenanceSink` dumps every prompt the LLM saw\n  plus every tool result into a diff-friendly directory, and pytest-style\n  `eval_*` functions turn that trace into a regression suite. Your debug\n  output *is* your eval harness.\n\nThat is the differentiation: looplet is not trying to be a complete\nagent product. It is the control plane for people building one.\n\n---\n\n## The mental model — one picture\n\n`looplet` is a `for` loop you own. The LLM proposes a tool call, the\nregistry dispatches it, hooks observe or steer, state records the result,\nand the loop yields a `Step`. The diagram below expands that simple story\ninto the hook points you can customize:\n\n```mermaid\n%%{init: {\"theme\":\"base\",\"themeVariables\":{\n  \"fontFamily\":\"ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif\",\n  \"fontSize\":\"15px\",\n  \"lineColor\":\"#94a3b8\"\n}}}%%\nflowchart LR\n    you([\"\u003cb\u003eyour code\u003c/b\u003e\u003cbr/\u003e\u003cspan style='font-size:11px;opacity:.75'\u003efor\u0026nbsp;step\u0026nbsp;in\u0026nbsp;loop(...)\u003c/span\u003e\"]):::you\n\n    h1[\"\u003cb\u003epre_prompt\u003c/b\u003e\u003cbr/\u003e\u003cspan style='font-size:11px;opacity:.9'\u003eredact\u0026nbsp;·\u0026nbsp;inject\u0026nbsp;·\u0026nbsp;compact\u003c/span\u003e\"]:::hookBlue\n    h2[\"\u003cb\u003epre_dispatch\u003c/b\u003e\u003cbr/\u003e\u003cspan style='font-size:11px;opacity:.9'\u003epermissions\u0026nbsp;·\u0026nbsp;approval\u0026nbsp;·\u0026nbsp;rewrite\u003c/span\u003e\"]:::hookAmber\n    h3[\"\u003cb\u003epost_dispatch\u003c/b\u003e\u003cbr/\u003e\u003cspan style='font-size:11px;opacity:.9'\u003etrace\u0026nbsp;·\u0026nbsp;metrics\u0026nbsp;·\u0026nbsp;checkpoint\u003c/span\u003e\"]:::hookAmber\n    h4[\"\u003cb\u003echeck_done\u003c/b\u003e\u003cbr/\u003e\u003cspan style='font-size:11px;opacity:.9'\u003estop\u0026nbsp;rules\u0026nbsp;·\u0026nbsp;budgets\u003c/span\u003e\"]:::hookGreen\n\n    subgraph loop[\" \"]\n      direction LR\n      prompt([\"\u003cb\u003ePROMPT\u003c/b\u003e\u003cbr/\u003e\u003cspan style='font-size:11px;opacity:.85'\u003ebuild\u0026nbsp;·\u0026nbsp;call\u0026nbsp;LLM\u003c/span\u003e\"]):::phaseBlue\n      dispatch([\"\u003cb\u003eDISPATCH\u003c/b\u003e\u003cbr/\u003e\u003cspan style='font-size:11px;opacity:.85'\u003evalidate\u0026nbsp;·\u0026nbsp;run\u0026nbsp;tool\u003c/span\u003e\"]):::phaseAmber\n      done{{\"\u003cb\u003eDONE?\u003c/b\u003e\"}}:::phaseGreen\n      prompt -- \"tool call\" --\u003e dispatch\n      dispatch -- \"observation\" --\u003e done\n      done -- \"no\" --\u003e prompt\n    end\n\n    step[/\"\u003cb\u003eStep\u003c/b\u003e\u003cbr/\u003e\u003cspan style='font-size:11px;opacity:.85'\u003eprompt\u0026nbsp;·\u0026nbsp;call\u0026nbsp;·\u0026nbsp;result\u0026nbsp;·\u0026nbsp;usage\u003c/span\u003e\"/]:::step\n\n    you == \"task\" ==\u003e prompt\n    done == \"yes\" ==\u003e step\n    step == \"yield\" ==\u003e you\n\n    h1 -.-\u003e prompt\n    h2 -.-\u003e dispatch\n    h3 -.-\u003e dispatch\n    h4 -.-\u003e done\n\n    linkStyle 0,1,2 stroke:#94a3b8,stroke-width:2px\n    linkStyle 3 stroke:#475569,stroke-width:3px\n    linkStyle 4 stroke:#059669,stroke-width:3px\n    linkStyle 5 stroke:#475569,stroke-width:3px\n    linkStyle 6 stroke:#3b82f6,stroke-width:1.5px\n    linkStyle 7 stroke:#f59e0b,stroke-width:1.5px\n    linkStyle 8 stroke:#f59e0b,stroke-width:1.5px\n    linkStyle 9 stroke:#10b981,stroke-width:1.5px\n\n    classDef you        fill:#0f172a,stroke:#334155,stroke-width:2px,color:#f8fafc;\n    classDef phaseBlue  fill:#dbeafe,stroke:#2563eb,stroke-width:2.5px,color:#1e3a8a;\n    classDef phaseAmber fill:#fef3c7,stroke:#d97706,stroke-width:2.5px,color:#78350f;\n    classDef phaseGreen fill:#d1fae5,stroke:#059669,stroke-width:2.5px,color:#064e3b;\n    classDef step       fill:#eef2ff,stroke:#4338ca,stroke-width:2.5px,color:#312e81;\n    classDef hookBlue   fill:#eff6ff,stroke:#3b82f6,stroke-width:1.5px,color:#1e40af;\n    classDef hookAmber  fill:#fffbeb,stroke:#f59e0b,stroke-width:1.5px,color:#92400e;\n    classDef hookGreen  fill:#ecfdf5,stroke:#10b981,stroke-width:1.5px,color:#065f46;\n\n    style loop fill:#f8fafc,stroke:#cbd5e1,stroke-width:2px,stroke-dasharray:10 6,color:#1e293b;\n```\n\nEvery amber box is a `Protocol` method. A hook is any object that\nimplements one or more of them — no base class, no inheritance:\n\n```python\nclass RedactPII:\n    def pre_prompt(self, state, log, ctx, step):\n        return _scrub_emails(ctx)          # mutates the next LLM prompt\n\nclass RetryFlakyTool:\n    def pre_dispatch(self, state, log, tc, step):\n        if tc.tool == \"web_search\" and state.last_error:\n            return Deny(\"retry with backoff\", retry=True)\n\nfor step in composable_loop(..., hooks=[RedactPII(), RetryFlakyTool()]):\n    ...\n```\n\nShip-ready hooks already wired in: `ApprovalHook`, `PermissionHook`,\n`CheckpointHook`, `ContextPressureHook`, `ThresholdCompactHook`,\n`ProvenanceSink`, `TracingHook`, `MetricsHook`, `EvalHook`, plus the\n`compact_chain(Prune, Summarize, Truncate)` context strategy. Use any,\nall, or none — and [drop in your own](docs/hooks.md) in 10 lines.\n\n---\n\n## Your first agent (60 seconds)\n\n```python\nfrom looplet import BaseToolRegistry, OpenAIBackend, composable_loop\nfrom looplet.tools import register_done_tool\n\nllm = OpenAIBackend.from_env(model=\"gpt-4o-mini\")  # reads OPENAI_API_KEY etc\n\ntools = BaseToolRegistry()\n\n\n@tools.tool\ndef greet(name: str) -\u003e dict:\n    \"\"\"Greet someone by name.\"\"\"\n    return {\"greeting\": f\"Hello, {name}!\"}\n\n\nregister_done_tool(tools)\n\nfor step in composable_loop(\n    llm=llm,\n    tools=tools,\n    task={\"goal\": \"Greet Alice and Bob, then finish.\"},\n    max_steps=5,\n):\n    print(step.pretty())\n```\n\nWorks out of the box with any OpenAI-compatible endpoint. No Claude-only\nSDK, no pydantic schema gymnastics, no LangChain memory objects.\n\nTry it on your laptop against a local Ollama in three lines:\n\n```bash\nOPENAI_BASE_URL=http://127.0.0.1:11434/v1 \\\nOPENAI_API_KEY=ollama OPENAI_MODEL=llama3.1 \\\npython -m looplet.examples.hello_world\n```\n\n---\n\n## When should you reach for `looplet`?\n\n**Use it when you want to build your own agent loop and actually own\nthe details.** Concretely:\n\n* You need to **insert logic at an exact phase** of the loop — before\n  the prompt is built, before a tool is dispatched, after a tool\n  returns — without forking a framework.\n* You need to **swap context-management strategy at runtime** (prune,\n  summarize, truncate, your own) without losing the rest of your stack.\n* You need the loop to **pause for human approval**, then resume where\n  it left off when approval arrives.\n* You want **first-class debugging and evaluation** — a printable\n  `Step`, a prompt-level provenance dump, pytest-style `eval_*`\n  functions — without bolting on a second tool.\n* You want **zero runtime dependencies** and a loop that cold-imports\n  in ~300 ms (numbers in [docs/benchmarks.md](docs/benchmarks.md)).\n\n**Don't reach for `looplet` if** you want `agent.run(task)` to handle\neverything and return a string, or if you want a visual graph DSL — a\nhigher-level framework will feel more natural and the overlap in\nfeatures won't be worth the extra control `looplet` gives you.\n\n---\n\n## Examples\n\nReal-LLM examples read `OPENAI_BASE_URL`, `OPENAI_API_KEY`, and\n`OPENAI_MODEL` from the environment. Point them at Ollama or any\nOpenAI-compatible endpoint, or use `--scripted` where available for a\ndeterministic no-model run.\n\n```bash\npython -m looplet.examples.hello_world                            # 30-line starter\npython -m looplet.examples.hello_world --scripted                 # no model required\npython -m looplet.examples.coding_agent \"implement fizzbuzz\"      # bash/read/write/edit/grep\npython -m looplet.examples.coding_agent --trace ./traces/         # save full trajectory\npython -m looplet.examples.coding_agent \"implement add\" --scripted --workspace /tmp/demo\npython -m looplet.examples.data_agent --clean                     # approval + compact + checkpoints\npython -m looplet.examples.data_agent --resume                    # resume from last checkpoint\npython -m looplet.examples.data_agent --scripted --auto-approve   # no model required\n```\n\nRunnable bundles package the same primitives behind a portable folder:\n\n```bash\npython -m looplet list-bundles tests/fixtures --json\npython -m looplet run tests/fixtures/coder_skill_bundle \"Create a tiny add function with tests\" --scripted --workspace /tmp/demo\npython -m looplet export-code tests/fixtures/coder_skill_bundle /tmp/coder_agent.py  # exact local wrapper\npython -m looplet package my_agent:build ./skills/my-agent --name my-agent --description \"Run my agent.\"\npython -m looplet wrap-claude-skill ./claude-skills/pdf ./skills/pdf\n```\n\nFor a memorable custom agent, start with **Dependency Doctor**: point it\nat a repo and it audits dependency files for security, license, and\nmaintenance risk, then produces a report card. It is concrete enough to\nbe useful, broad enough that most developers understand the pain, and it\nshows looplet's core value: the user can watch every evidence-gathering\nstep and add guardrails without rewriting the agent.\n\n```bash\n# Load the v2 workspace; pass --workspace to point at the project to audit.\nOPENAI_BASE_URL=http://127.0.0.1:11434/v1 \\\nOPENAI_API_KEY=ollama OPENAI_MODEL=llama3.1 \\\npython -c \"from looplet import workspace_to_preset; \\\np = workspace_to_preset('examples/dep_doctor.workspace', runtime={'workspace': '/path/to/project'})\"\n```\n\nOther example directions that show off the same infrastructure:\n`examples/git_detective.workspace/` for repo-health analysis,\n`examples/threat_intel.workspace/` for local-first security briefings, and\n`examples/coder.workspace/` for a coding agent with bash/read/write/edit/test\ntools. Each is a self-contained Composable Harness Workspace that\nround-trips losslessly with an `AgentPreset` via `preset_to_workspace`\n/ `workspace_to_preset`.\n\n```bash\n# More dogfood — load each workspace and run a scripted loop.\npython -m looplet.examples.hello_world --scripted\npython -m looplet.examples.ollama_hello --scripted\npython -m looplet.examples.coding_agent \"Implement add\" --scripted --workspace /tmp/demo\npython -m looplet.examples.data_agent --scripted --auto-approve --clean\n```\n\nPlus [`scripted_demo.py`](src/looplet/examples/scripted_demo.py) —\na scripted `MockLLMBackend` run used only to record the GIF above.\nNot a usage reference.\n\n---\n\n## Learn more\n\n| Doc | What's in it |\n| --- | --- |\n| [docs/tutorial.md](docs/tutorial.md) | Build your first agent in 5 steps |\n| [docs/hooks.md](docs/hooks.md) | Writing and composing hooks |\n| [docs/skills.md](docs/skills.md) | Lazy skills, runnable bundles, blueprints, and Claude Skill wrapping |\n| [docs/evals.md](docs/evals.md) | pytest-style agent evaluation |\n| [docs/provenance.md](docs/provenance.md) | Capturing prompts + trajectories |\n| [docs/recipes.md](docs/recipes.md) | Ollama, OTel, MCP, cost accounting, checkpoints |\n| [docs/benchmarks.md](docs/benchmarks.md) | Cold-import time \u0026 dep footprint vs alternatives |\n| [docs/faq.md](docs/faq.md) | FAQ, including \"why not LangGraph?\" |\n| [ROADMAP.md](ROADMAP.md) | What's planned, what's frozen, what's out of scope |\n| [CONTRIBUTING.md](CONTRIBUTING.md) | Dev setup, conventions, PR checklist |\n| [CHANGELOG.md](CHANGELOG.md) | Release notes |\n\n---\n\n## Stability\n\n`looplet` follows [SemVer](https://semver.org/). Pre-`1.0`, minor versions\nmay introduce breaking changes as the design stabilises — pin conservatively:\n\n```toml\nlooplet\u003e=0.1.8,\u003c0.2\n```\n\nSee [ROADMAP.md § v1.0 API contract](ROADMAP.md#v10-api-contract) for the\nfrozen surface and the path to `1.0`.\n\n## Contributors\n\nThanks to everyone who has contributed to `looplet`:\n\n- [@mvanhorn](https://github.com/mvanhorn) - \"Why not LangGraph?\" FAQ (#17)\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for how to get started.\n\n## Contributing\n\nContributions welcome: bug reports, docs, backends, examples, evals.\nStart with [CONTRIBUTING.md](CONTRIBUTING.md) and\n[docs/good-first-issues.md](docs/good-first-issues.md). Security issues\ngo through [SECURITY.md](SECURITY.md).\n\n## License\n\nApache 2.0. See [LICENSE](LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhsaghir%2Flooplet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhsaghir%2Flooplet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhsaghir%2Flooplet/lists"}