query-loop-implementation

query-loop-implementation is a skill for Claude Code, Codex from simbajigege/book2skills. It costs 75 tokens per session (1,241 once invoked), scanned A, original, MIT.

A production-oriented loop for applications where a language model can call tools, receive their results, and continue until it answers or reaches an exit limit. It separates conversation state, the task loop, and tool execution.

In plain words
What is it for?
Use it to add function or tool calling, ReAct-style agent cycles, query engines, tool-result feedback, maximum-turn exits, or Claude Code-like agent behavior to an AI application.
Why use it?
It replaces fragile prompt-based tool handling with structured model calls, permission checks, error formatting, and explicit stopping rules. This makes tool feedback and session state easier to manage.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/simbajigege/book2skills/query-loop-implementation
Any agent
npx skills add simbajigege/book2skills --skill query-loop-implementation
Clone the repo
git clone --depth 1 https://github.com/simbajigege/book2skills

Made for: Claude Code, Codex.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for query-loop-implementation

README.md
[![agentmods](https://agentmods.dev/badge/skills/simbajigege/book2skills/query-loop-implementation.svg)](https://agentmods.dev/skills/simbajigege/book2skills/query-loop-implementation)
Your own site
<a href="https://agentmods.dev/skills/simbajigege/book2skills/query-loop-implementation"><img src="https://agentmods.dev/badge/skills/simbajigege/book2skills/query-loop-implementation.svg" alt="Measured on agentmods" height="20"></a>
Per session 75 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 1,241 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00075 $0.01241
Opus 5 $0.00037 $0.00620
Sonnet 5 $0.00015 $0.00248
Haiku 4.5 $0.00007 $0.00124

Measured 6d ago against content hash cf6555ee5332, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-05, from the pricing page.

Security

Grade A, and why

query-loop-implementation scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 6d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/query-loop-implementation/SKILL.md · 171 lines

How it starts

The opening of the file, as written. The whole thing — 171 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Query Loop Implementation

Core Idea

Build the loop as product infrastructure, not prompt glue:

ConversationManager -> QueryLoop -> ToolRuntime
  • ConversationManager owns durable state: session id, messages, user settings, budget, persistence.
  • QueryLoop owns one task turn: call model, detect tool calls, execute tools, append tool results, repeat.
  • ToolRuntime owns registered tools: schemas, permission checks, execution, error formatting.

Use ReAct as the mental model:

Thought -> Action -> Observation -> Thought -> Answer

Implement it as structured API traffic:

model thinking/text -> tool_call -> tool_result -> next model call -> final text

Implementation Workflow

  1. Inspect the user's stack and current LLM call site. Find where messages are built, where the model is called, and whether tool/function calling is already configured.

  2. Introduce a minimal query loop. Keep the first version narrow: one model call function, one tool registry, explicit exit conditions.

  3. Normalize message shapes. Use the provider's structured tool-call format when available. Avoid parsing free-form Action: text unless the provider has no function/tool-calling API.

  4. Add tool execution safety. Validate tool input against a schema, apply permission checks for risky tools, wrap failures as tool results, and log every call.

  5. Add exit and budget guards before expanding features. Always include maxTurns, timeout/cancel support, token/cost budget checks, and a fatal-error path.

  6. Keep context-window strategy outside this skill. Accept messages as loop input and return updated messages, but leave trimming, retrieval, summarization, and compaction to a separate context-management layer.

Minimal Loop

Adapt this shape to the user's language and SDK:

async function runQueryLoop({
  initialMessages,
  model,
  tools,
  maxTurns = 10,
  signal,
}: {
  initialMessages: Message[]
  model: ModelClient
  tools: ToolRegistry
  maxTurns?: number
  signal?: AbortSignal
}) {
  let messages = [...initialMessages]

  for (let turn = 1; turn <= maxTurns; turn++) {
    if (signal?.aborted) return { status: "aborted", messages }

    const response = await model.generate({
      messages,
      tools: tools.definitions(),
      signal,
    })

    messages.push(response.message)

    const toolCalls = extractToolCalls(response.message)
    if (toolCalls.length === 0) {
      return {
        status: "completed",
        finalMessage: response.message,
        messages,
      }
    }

    for (const call of toolCalls) {
      const result = await tools.execute(call, { signal, messages })
      messages.push(makeToolResultMessage(call.id, result))
    }
  }

  return { status: "max_turns", messages }
}

Read the full file on GitHub · 171 lines

Files

What ships with it

5 files beside SKILL.md in the same directory: the scripts, references and assets a skill reads on demand. Not counted in the per-session cost; read them before you install if any of them is executable.

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 6d ago First seen · 171 lines · 75 tokens per session scan A cf6555ee5332

Subscribe to this mod's changes

query-loop-implementation is a skill published in the GitHub repository simbajigege/book2skills (156 stars, last pushed 10d ago), licensed MIT. It adds 75 tokens to every session and 1,241 once invoked, about $0.0004 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

skill-check

Validate Claude Code skills against the agentskills specification. Catches structural, semantic, and naming issues before users do.

ratnesh-maurya/cursor-claude-personas · 26 tokens

llm-app-patterns

Production-ready patterns for building LLM applications. Covers RAG pipelines, agent architectures, prompt IDEs, and LLMOps monitoring. Use when designing AI applications, implementing RAG, building agents, or setting up LLM observability.

davila7/claude-code-templates · 54 tokens

langsmith-observability

LLM observability platform for tracing, evaluation, and monitoring. Use when debugging LLM applications, evaluating model outputs against datasets, monitoring production systems, or building systematic testing pipelines for AI applications.

davila7/claude-code-templates · 45 tokens

crewai

Expert in CrewAI - the leading role-based multi-agent framework used by 60% of Fortune 500 companies. Covers agent design with roles and goals, task definition, crew orchestration, process types (sequential, hierarchical, parallel), memory systems, and flows for complex workflows. Essential for building collaborative…

davila7/claude-code-templates · 89 tokens

research-engineer

An uncompromising Academic Research Engineer. Operates with absolute scientific rigor, objective criticism, and zero flair. Focuses on theoretical correctness, formal verification, and optimal implementation across any required technology.

davila7/claude-code-templates · 43 tokens

context7-auto-research

Automatically fetch latest library/framework documentation for Claude Code via Context7 API.

davila7/claude-code-templates · 19 tokens