ai-agent-core-loop
Use when the user asks about the agent loop, ReAct vs plan-and-solve, re-planning, Reflexion, an agent stuck in a loop, max iterations or termination…
by j4flmao★ 47 GitHub stars
Install ai-agent-core-loop in Claude Code & Claude Desktop
Sign up to install this skill
Create a free account to reveal the install command and save the skill to your library.
- Reveal the one-line install command
- Save skills to your synced library
- Get notified when skills update
About this skill
Agent Core Loop
Purpose
Every agent reduces to a loop: build context from state, ask the model for the next action, execute it, record the observation, decide whether to stop. Reliability comes from the parts around the model call: how context is assembled, how actions are validated, how progress is measured, and when the loop terminates. This skill covers those mechanics and the trade-offs between ReAct, plan-and-solve, and reflection variants.
Agent Protocol
Trigger
"agent loop", "ReAct", "plan-and-solve", "re-planning", "self-reflection", "Reflexion", "agent stuck in a loop", "termination condition", "max iterations".
Input Context
- Current loop code or framework config.
- Typical task length and failure transcripts (where it loops, stalls, or stops early).
- Tool list with side-effect classification.
Output Artifact
Loop specification or patch: state object, step function, termination rules, reflection policy.
Response Format
Variant: {react|plan-and-solve|plan-execute-replan|reflexion}
State: {fields}
Step: assemble_context -> decide -> validate -> execute -> observe -> update
Stop when: {success test} OR steps>={n} OR no_progress>={k} OR budget>={usd}
Reflection: {trigger, input signal, where lessons are stored}
Completion Criteria
- Success is a checkable predicate, not "model says done".
- Explicit caps and a no-progress detector.
- Actions validated before execution.
- Reflection uses an external signal (test result, error, evaluator), not introspection alone.
The Loop as a State Machine
flowchart TD
Start([Goal]) --> Ctx[Assemble context: goal, plan, recent observations]
Ctx --> Decide[Model proposes action or final answer]
Decide --> Check{Final answer?}
Check -- yes --> Verify{Success predicate holds?}
Verify -- yes --> Done([Return])
Verify -- no --> Reflect[Record failure reason] --> Ctx
Check -- no --> Validate{Schema + policy valid?}
Validate -- no --> Ctx
Validate -- yes --> Exec[Execute tool] --> Obs[Append observation, update state]
Obs --> Guard{Caps or no-progress hit?}
Guard -- yes --> Abort([Abort with partial result])
Guard -- no --> Ctx
Variants
| Variant | How it works | Strength | Weakness |
|---|---|---|---|
| ReAct | Decide one action at a time from latest observation | Adapts to surprises | Drifts on long tasks; myopic |
| Plan-and-solve | Write full plan, then execute in order | Coherent on long tasks | Brittle when a step fails |
| Plan-execute-replan | Plan, execute one step, revise remaining plan | Coherent and adaptive | Extra LLM call per step |
| Reflexion | After a failed attempt, write a verbal lesson; retry with lessons in context | Learns across attempts | Needs a reliable failure signal |
| LLMCompiler-style | Plan a DAG of tool calls, run independent ones in parallel | Lower latency | Planning errors propagate |
Rule of thumb: start with ReAct for short tasks (< ~10 steps); add an explicit plan object once tasks get longer or drift appears; add reflection only when you have an automatic success test.
Reference Implementation (framework-agnostic)
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass, field
from typing import Any, Callable, Protocol
class Policy(Protocol):
def decide(self, context: str) -> dict[str, Any]: ... # {"type": "tool"|"final", ...}
@dataclass
class LoopState:
goal: str
plan: list[str] = field(default_factory=list)
observations: list[str] = field(default_factory=list)
lessons: list[str] = field(default_factory=list)
seen_calls: dict[str, int] = field(default_factory=dict)
steps: int = 0
steps_without_progress: int = 0
class LoopAborted(RuntimeError):
pass
def run_loop(
state: LoopState,
policy: Policy,
tools: dict[str, Callable[..., str]],
is_success: Callable[[str, LoopState], bool],
max_steps: int = 15,
max_no_progress: int = 3,
) -> str:
while state.steps < max_steps:
state.steps += 1
context = "\n".join([
f"GOAL: {state.goal}",
"PLAN:\n" + "\n".join(state.plan),
"LESSONS:\n" + "\n".join(state.lessons[-5:]),
"RECENT OBSERVATIONS:\n" + "\n".join(state.observations[-6:]),
])
action = policy.decide(context)
if action["type"] == "final":
if is_success(action["answer"], state):
return action["answer"]
state.lessons.append(f"Answer rejected by success check at step {state.steps}")
continue
name, args = action["tool"], action.get("args", {})
if name not in tools:
state.observations.append(f"ERROR: unknown tool '{name}'. Valid: {sorted(tools)}")
continue
key = hashlib.sha256(json.dumps([name, args], sort_keys=True).encode()).hexdigest()
state.seen_calls[key] = state.seen_calls.get(key, 0) + 1
Allowed tools
Tools this skill is permitted to call.
No restriction — this skill can use any tool.
Bundled files
- references/react-pattern.md
- references/reflexion.md
FAQ
What does the ai-agent-core-loop skill do?
Use when the user asks about the agent loop, ReAct vs plan-and-solve, re-planning, Reflexion, an agent stuck in a loop, max iterations or termination conditions. Produces a loop spec or patch with state, success predicate, caps and no-progress detection. Not for overall agent design (use ai-agent-architectures) or tool schemas (use tool-calling-principles).
How do I install the ai-agent-core-loop skill?
Copy the skill folder into ~/.claude/skills (the Claude Code tab above does this in one command), or install it as a plugin.
Does the ai-agent-core-loop skill run scripts?
No, this skill is instructions only (SKILL.md) with no executable scripts.
Related skills
frontend-design
AnthropicGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
webapp-testing
AnthropicToolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
brand-guidelines
AnthropicApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
web-artifacts-builder
AnthropicSuite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…