Logo vun Ai Agent Core Loop

Ai Agent Core Loop

Communautéit
j4flmao
ai-agent-core-loop

Use this skill when the user says 'agent loop', 'perceive think act', 'ReAct vs plan-and-solve', 'agent keeps looping', 'agent self-reflection', 'Reflexion', 'agent termination condition'. Explains and implements the mechanics of a single agent's control loop: observation assembly, action selection, termination, re-planning, and reflection. Do NOT use for: overall agent design (ai/ai-agents), workflow pattern selection (ai/agentic-workflows), tool schemas (ai/ai-agents/tool-calling-principles), or memory stores (ai/ai-agents/memory-systems).

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummai-agent-core-loop
Stären
41
Forks
6
Matgeliwwert Fichieren
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    Vum j4flmao op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Ai Agent Core Loop an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/ai-agents/core-architectures
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/ai/ai-agents/core-architectures .claude/skills/ai-agent-core-loop
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Ai Agent Core Loop an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Ai Agent Core Loop automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Ai Agent Core Loop net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

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

Variants

VariantHow it worksStrengthWeakness
ReActDecide one action at a time from latest observationAdapts to surprisesDrifts on long tasks; myopic
Plan-and-solveWrite full plan, then execute in orderCoherent on long tasksBrittle when a step fails
Plan-execute-replanPlan, execute one step, revise remaining planCoherent and adaptiveExtra LLM call per step
ReflexionAfter a failed attempt, write a verbal lesson; retry with lessons in contextLearns across attemptsNeeds a reliable failure signal
LLMCompiler-stylePlan a DAG of tool calls, run independent ones in parallelLower latencyPlanning 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)

python
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
        if state.seen_calls[key] > 2:
            state.observations.append(f"NOTE: {name} called 3x with identical args; change approach.")
            state.steps_without_progress += 1
        else:
            try:
                result = tools[name](**args)
                state.observations.append(f"{name} -> {result[:2000]}")
                state.steps_without_progress = 0
            except Exception as exc:
                state.observations.append(f"{name} FAILED: {type(exc).__name__}: {exc}")
                state.steps_without_progress += 1

        if state.steps_without_progress >= max_no_progress:
            raise LoopAborted(f"no progress for {max_no_progress} steps; last: {state.observations[-1]}")
    raise LoopAborted(f"step cap {max_steps} reached for goal: {state.goal[:80]}")

Termination Rules

  1. Success predicate: tests pass, schema validates, the user-visible artifact exists. Never trust "I am done" alone.
  2. Hard caps: steps, tokens, wall clock, money.
  3. No-progress detector: repeated identical calls, repeated identical errors, or no state change for k steps.
  4. Escalation: on abort, return partial results plus the reason, and route to a human when the task matters.

Reflection Done Right

  • Trigger on a concrete failure (test failure, exception, evaluator rejection).
  • Feed the failure evidence, not just "try again".
  • Store lessons as short imperative notes ("run migrations before tests"), cap how many are kept, and drop stale ones.
  • Measure: a reflection step that does not raise the success rate on your eval set is pure cost.

Anti-Patterns

  • Asking the model whether it succeeded instead of checking.
  • Unlimited history: early constraints scroll out or get diluted; keep goal and plan pinned.
  • Parsing free-text "Action:" lines when native tool calling is available.
  • Retrying the same failing call with identical arguments.
  • Planning once and never revising.

Checklist

  • State object with goal, plan, observations, lessons, counters.
  • Context assembly pins goal/plan; observations truncated and windowed.
  • Unknown tools and invalid args returned as observations, not crashes.
  • Duplicate-call and no-progress detection.
  • Success predicate implemented in code.
  • Abort path returns partial work and reason.

References

  • Yao et al., "ReAct" (ICLR 2023); Shinn et al., "Reflexion" (NeurIPS 2023); Kim et al., "An LLM Compiler for Parallel Function Calling" (ICML 2024).
  • Parent: ../SKILL.md; planning detail: ../references/planning-strategies.md.

Heefeg gestallte Froen

Wat mécht de KI-Skill Ai Agent Core Loop?

Use this skill when the user says 'agent loop', 'perceive think act', 'ReAct vs plan-and-solve', 'agent keeps looping', 'agent self-reflection', 'Reflexion', 'agent termination condition'. Explains and implements the mechanics of a single agent's control loop: observation assembly, action selection, termination, re-planning, and reflection. Do NOT use for: overall agent design (ai/ai-agents), workflow pattern selection (ai/agentic-workflows), tool schemas (ai/ai-agents/tool-calling-principles), or memory stores (ai/ai-agents/memory-systems).

Firwat Ai Agent Core Loop op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Ai Agent Core Loop besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Ai Agent Core Loop an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/ai/ai-agents/core-architectures an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Ai Agent Core Loop benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Ai Agent Core Loop benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Ai Agent Core Loop domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Ai Agent Core Loop gratis?

Jo. De Skill gëtt vum j4flmao ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇