
Prompt Repetition
- 211 installs
- 40 repo stars
- Updated August 4, 2026
- akillness/oh-my-skills
Detect and break prompt repetition loops in long agent sessions to reduce token waste, stale answers, and runaway re-asks during implementation tasks.
About
prompt-repetition from oh-my-skills monitors agent dialogs for circular prompts and near-duplicate instructions, then intervenes with de-duplication guidance and recovery steps to keep builds moving efficiently.
- Repetition loop detection
- Prompt de-duplication hints
- Token waste reduction
- Session reset triggers
- Stuck-agent recovery prompts
Prompt Repetition by the numbers
- 211 all-time installs (skills.sh)
- Ranked #2,807 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/akillness/oh-my-skills --skill prompt-repetitionAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 211 |
|---|---|
| repo stars | ★ 40 |
| Last updated | August 4, 2026 |
| Repository | akillness/oh-my-skills ↗ |
What it does
Detect and break prompt repetition loops in long agent sessions to reduce token waste, stale answers, and runaway re-asks during implementation tasks.
Files
Prompt Repetition
When to use this skill
- The user is using a non-reasoning or lightweight model and accuracy drops when the important question appears late in the prompt.
- The prompt shape is long-context retrieval, options-first multiple choice, or position-sensitive lookup.
- The user wants a bounded decision rule for whether to duplicate the prompt 2× or 3×, not a vague promise that prompt engineering will help.
- The workflow needs a cheap experiment before changing models or building retrieval infrastructure.
- The request mentions things like the model forgot the question, missed the final instruction, lost the item at slot 25, got confused by a long options list, or performs worse on Haiku / Flash / mini models than on stronger reasoning models.
Do not use this skill as the main workflow when:
- The real problem is context selection, retrieval design, or noisy source stuffing → use broader context-engineering or RAG work.
- The real problem is reasoning depth and a reasoning-capable model is available.
- The prompt is tool-heavy / agentic / multi-step, where duplicating the full prompt may just multiply cost and confusion.
- The user needs a universal always-on middleware policy. This skill is for targeted use, not blanket auto-apply.
Core idea
Prompt repetition is a task-shape-specific intervention, not a universal prompting law.
The strongest evidence-backed cases are: 1. Long-context retrieval — the question comes after a lot of context and the model misses late details. 2. Options-first MCQ — choices appear before the question or the structure makes the actual ask easy to lose. 3. Position-sensitive lookup — inventories, ordered lists, or record positions where the model loses track of index-like detail.
The skill succeeds when it answers three questions clearly: 1. Is this one of the task shapes where repetition is worth testing? 2. What repetition count is safe enough to try without blowing the context budget? 3. What should we do instead if repetition is the wrong tool?
Instructions
Step 1: Classify the prompt shape before changing anything
Put the current prompt into one bucket:
| Shape | Typical signal | Repetition fit | Better alternative if fit is weak |
|---|---|---|---|
| Long-context retrieval | "The model ignores the question after a huge context block" | Good | Trim/select context, retrieval, restate question near end |
| Options-first MCQ | "The options come first and the model picks the wrong letter" | Good | Reorder question/options, simplify answer format |
| Position-sensitive lookup | "It misses item 25 in a long list" | Good | Chunk the list, provide structured table, use retrieval |
| Tool-heavy agent prompt | "There are many tools, policies, and steps" | Weak | Simplify policy, separate stages, use better orchestration |
| Reasoning-heavy task | "We need step-by-step synthesis or planning" | Weak | Use a reasoning model, decomposition, examples |
| RAG / search architecture | "The retrieved evidence is noisy or incomplete" | Weak | Fix retrieval, ranking, chunking, context packing |
If the task lands in a weak row, do not recommend prompt repetition as the main answer.
Step 2: Check the model and cost guardrail
Prompt repetition multiplies input tokens, even if the paper reports no increase in generated output length or latency for the tested runs.
Minimum checks:
- Model class — is this a non-reasoning / lightweight model or a stronger reasoning-capable model?
- Prompt length now — estimate whether 2× or 3× would still fit comfortably inside the usable context budget.
- Operational budget — is extra input cost acceptable for this workflow?
- Failure mode — are we fixing a late-context miss, or is the task actually about reasoning or retrieval quality?
Conservative default:
- if the prompt is already near the context limit, do not recommend full repetition
- if the task needs structured reasoning, do not use repetition as a substitute for model choice
- if only the final question/instruction matters, try restating the question before duplicating the whole prompt
Step 3: Choose the smallest useful intervention
Use the cheapest intervention that matches the failure:
1. Repeat the question only
- Best when the context is huge but only the final ask is being lost.
- Cheapest first experiment.
2. Repeat the full prompt 2×
- Default experiment for long-context retrieval and options-first MCQ on lightweight models.
- Good first pass when the whole prompt structure matters.
3. Repeat the full prompt 3×
- Reserve for clearly position-sensitive or index-heavy tasks.
- Only if the cost and context window are still safe.
If the user cannot afford the input-token overhead, route to prompt restructuring or retrieval instead.
Step 4: Apply explicit opt-out rules
Do not recommend repetition when any of these are true:
- the user already has a good reasoning model and the failure is multi-step reasoning
- the prompt includes many tools, policies, or action constraints that would just be duplicated noisily
- the retrieval set is weak, contradictory, or irrelevant
- the context budget is already tight enough that duplication risks truncation or degraded performance
- the task can be fixed more cleanly by moving the question, reducing context, or adding a small example
Step 5: Return a decision, not just a trick
A good answer should include: 1. Fit — why repetition is or is not appropriate here 2. Smallest recommended intervention — repeat question only, full prompt 2×, full prompt 3×, or do not use repetition 3. Budget note — input-token / context-window implication 4. Fallback / route-out — what to do instead if repetition is the wrong tool
Use this response shape:
"This is a [good / weak] fit for prompt repetition because [task shape]. I would try [smallest intervention] first. Watch [token/context risk]. If that fails, switch to [better alternative]."
Step 6: Keep evaluation narrow and comparable
When testing repetition:
- use the same prompt except for the repetition change
- compare baseline vs 2× vs 3× only when the budget allows
- judge success on task accuracy, not on style or length alone
- stop if the repeated prompt causes context pressure or obvious prompt bloat
If more than one change is needed, repetition is probably not the main lever.
Step 7: Route out when another job starts
- Context selection / retrieval / chunking / source quality → broader context-engineering or RAG work
- Reasoning-heavy synthesis / planning → stronger reasoning model or decomposition workflow
- Prompt examples / output-format steering → few-shot or prompt-structure work
- Tool-policy / action-constraint confusion → simplify orchestration instead of duplicating the whole prompt
Examples
Example 1: Options-first MCQ on a lightweight model
Prompt:
I have a long options-first multiple-choice prompt on a Flash model. Should I duplicate the prompt or restructure it?
Good response shape:
- classify as options-first MCQ
- recommend either question restatement or full prompt 2× as the first bounded experiment
- mention token-cost tradeoff
- note that reordering the prompt is a valid structural alternative
Example 2: RAG quality complaint
Prompt:
Our RAG answers are weak. Should we add prompt repetition everywhere?
Good response shape:
- say this is a weak fit
- explain that retrieval/context quality is the bigger lever
- route to context engineering or RAG fixes instead of blanket repetition
Example 3: Position-sensitive inventory lookup
Prompt:
A mini model keeps missing the item at slot 25 in a long inventory list.
Good response shape:
- classify as position-sensitive lookup
- allow 2× and possibly 3× repetition if budget permits
- mention structured-table or chunking fallback if cost is too high
Example 4: Reasoning model question
Prompt:
We have a reasoning-capable model available, but it is more expensive. Does prompt repetition replace it?
Good response shape:
- say no, repetition is not a substitute for reasoning ability
- limit repetition to targeted non-reasoning failure modes
- route multi-step reasoning to the stronger model or decomposition
Best practices
1. Treat prompt repetition as a targeted experiment, not default middleware. 2. Start with the smallest intervention that matches the failure mode. 3. Always mention input-token cost and context-budget pressure. 4. Prefer prompt restructuring or retrieval fixes when the real issue is context quality. 5. Drop weakly evidenced claims instead of letting the skill become a generic prompt-hacks bucket. 6. Keep the final recommendation binary: try repetition here or route elsewhere.
References
- references/evidence-and-boundaries.md
- references/operator-checklist.md
{
"skill_name": "prompt-repetition",
"evals": [
{
"id": 1,
"prompt": "I have a long options-first multiple-choice prompt on a Flash model. Should I duplicate the prompt or restructure it?",
"expected_output": "Classifies the task as a good fit for prompt repetition, recommends question restatement or full prompt 2x as the first bounded experiment, mentions input-token cost, and notes that reordering the prompt is a valid alternative.",
"assertions": [
"Response classifies the prompt shape before recommending a change",
"Response mentions token or context-budget cost",
"Response offers prompt restructuring as an alternative instead of claiming repetition is mandatory"
]
},
{
"id": 2,
"prompt": "Our RAG answers are weak. Should we add prompt repetition everywhere?",
"expected_output": "Says prompt repetition is a weak fit, explains that retrieval or context quality is the bigger lever, and routes to broader context-engineering or RAG work.",
"assertions": [
"Response does not recommend blanket auto-apply",
"Response distinguishes repetition from retrieval or context-quality work",
"Response routes to a broader context-engineering or RAG fix"
]
},
{
"id": 3,
"prompt": "A mini model keeps missing the item at slot 25 in a long inventory list.",
"expected_output": "Classifies the task as a position-sensitive lookup, allows 2x or 3x repetition if budget permits, and mentions structured-table or chunking fallbacks.",
"assertions": [
"Response recognizes position-sensitive or index-heavy lookup",
"Response limits 3x repetition to a bounded case instead of making it universal",
"Response includes a non-repetition fallback such as chunking or structured formatting"
]
}
]
}
#!/usr/bin/env python3
"""
Prompt Repetition Transformer
경량 모델(haiku, flash, mini)에서 자동으로 프롬프트 반복을 적용하여
LLM 정확도를 향상시키는 변환기입니다.
Google Research 2025 연구 기반:
- 70개 벤치마크 중 67%(47/70)에서 유의미한 성능 향상
- 최대 +76%p 개선 (Gemini 2.0 Flash-Lite on NameIndex)
- 지연 시간 증가 +2% (Prefill 병렬화)
Usage:
from prompt_repetition_transformer import PromptRepetitionTransformer
transformer = PromptRepetitionTransformer()
improved_prompt = transformer.transform(prompt, model="claude-haiku")
"""
from dataclasses import dataclass
from typing import Optional, Callable, List, Dict
import re
# 모델별 컨텍스트 윈도우 (토큰 수)
MODEL_CONTEXT_WINDOWS: Dict[str, int] = {
"claude-3-haiku": 200_000,
"claude-haiku": 200_000,
"gemini-flash": 1_000_000,
"gemini-flash-lite": 1_000_000,
"gemini-2.0-flash": 1_000_000,
"gpt-4o-mini": 128_000,
"gpt-low": 128_000,
}
# 자동 적용 대상 모델
AUTO_APPLY_MODELS: List[str] = list(MODEL_CONTEXT_WINDOWS.keys())
# CoT 패턴 (적용 제외)
COT_PATTERNS: List[str] = [
r"step by step",
r"think through",
r"let's think",
r"reasoning:",
r"chain of thought",
r"단계별로",
r"차근차근",
]
# Position/Index 패턴 (3회 반복)
POSITION_PATTERNS: List[str] = [
r"slot \d+",
r"position \d+",
r"index \d+",
r"\d+번째",
r"item \d+",
r"row \d+",
r"column \d+",
r"슬롯 \d+",
r"위치 \d+",
]
@dataclass
class PromptRepetitionConfig:
"""프롬프트 반복 설정"""
default_repetitions: int = 2
position_repetitions: int = 3
separator: str = "\n\n"
max_context_ratio: float = 0.8
applied_marker: str = "<!-- prompt-repetition-applied -->"
class PromptRepetitionTransformer:
"""경량 모델용 프롬프트 반복 자동 적용 변환기
Example:
>>> transformer = PromptRepetitionTransformer()
>>> prompt = "A. Paris\\nB. London\\n\\nWhat is the capital of France?"
>>> result = transformer.transform(prompt, "claude-haiku")
>>> # 프롬프트가 2회 반복됨
"""
def __init__(self, config: Optional[PromptRepetitionConfig] = None):
self.config = config or PromptRepetitionConfig()
def should_apply(self, model: str, prompt: str) -> bool:
"""자동 적용 여부 결정
Args:
model: 모델 이름 (예: claude-haiku, gemini-flash)
prompt: 원본 프롬프트
Returns:
적용 여부 (True/False)
"""
# 이미 적용된 경우 스킵
if self.config.applied_marker in prompt:
return False
# 대상 모델 확인
model_lower = model.lower()
if not any(m in model_lower for m in AUTO_APPLY_MODELS):
return False
# CoT 패턴 감지 시 스킵
prompt_lower = prompt.lower()
for pattern in COT_PATTERNS:
if re.search(pattern, prompt_lower):
return False
return True
def determine_repetitions(self, prompt: str, model: str) -> int:
"""작업 유형에 따른 반복 횟수 결정
Args:
prompt: 프롬프트 내용
model: 모델 이름
Returns:
반복 횟수 (2 또는 3)
"""
prompt_lower = prompt.lower()
# Position/Index 패턴 감지 → 3회
for pattern in POSITION_PATTERNS:
if re.search(pattern, prompt_lower):
return self.config.position_repetitions
return self.config.default_repetitions
def estimate_tokens(self, text: str) -> int:
"""간단한 토큰 수 추정 (정확도보다 속도 우선)
Args:
text: 텍스트
Returns:
추정 토큰 수
"""
# 영어: 평균 4자 = 1토큰
# 한국어: 평균 2자 = 1토큰 (보수적 추정)
# 혼합 추정: 3자 = 1토큰
return len(text) // 3
def get_max_context(self, model: str) -> int:
"""모델별 최대 컨텍스트 윈도우 반환
Args:
model: 모델 이름
Returns:
최대 토큰 수
"""
model_lower = model.lower()
for m, tokens in MODEL_CONTEXT_WINDOWS.items():
if m in model_lower:
return tokens
return 128_000 # 기본값
def transform(self, prompt: str, model: str) -> str:
"""프롬프트에 반복 적용
Args:
prompt: 원본 프롬프트
model: 모델 이름
Returns:
변환된 프롬프트 (반복 적용됨)
"""
if not self.should_apply(model, prompt):
return prompt
repetitions = self.determine_repetitions(prompt, model)
# 컨텍스트 제한 체크
max_tokens = self.get_max_context(model)
max_allowed = int(max_tokens * self.config.max_context_ratio)
prompt_tokens = self.estimate_tokens(prompt)
# 토큰 제한 초과 시 반복 횟수 조정
while prompt_tokens * repetitions > max_allowed and repetitions > 1:
repetitions -= 1
if repetitions <= 1:
return prompt
# 반복 적용 + 마커 추가
repeated = self.config.separator.join([prompt] * repetitions)
return f"{self.config.applied_marker}\n{repeated}"
def wrap_llm_call(self, llm_fn: Callable, model: str) -> Callable:
"""LLM 호출 함수 래핑
Args:
llm_fn: 원본 LLM 호출 함수
model: 모델 이름
Returns:
래핑된 함수
"""
def wrapped(prompt: str, **kwargs):
transformed = self.transform(prompt, model)
return llm_fn(transformed, **kwargs)
return wrapped
def apply_prompt_repetition(prompt: str, times: int = 2, separator: str = "\n\n") -> str:
"""간단한 프롬프트 반복 함수
Args:
prompt: 원본 프롬프트
times: 반복 횟수 (기본 2회)
separator: 반복 간 구분자
Returns:
반복된 프롬프트
"""
if times <= 1:
return prompt
return separator.join([prompt] * times)
# 편의 함수
def is_lightweight_model(model: str) -> bool:
"""경량 모델 여부 확인"""
model_lower = model.lower()
return any(m in model_lower for m in AUTO_APPLY_MODELS)
def has_cot_pattern(prompt: str) -> bool:
"""CoT 패턴 포함 여부 확인"""
prompt_lower = prompt.lower()
for pattern in COT_PATTERNS:
if re.search(pattern, prompt_lower):
return True
return False
def has_position_pattern(prompt: str) -> bool:
"""Position/Index 패턴 포함 여부 확인"""
prompt_lower = prompt.lower()
for pattern in POSITION_PATTERNS:
if re.search(pattern, prompt_lower):
return True
return False
if __name__ == "__main__":
# 테스트
transformer = PromptRepetitionTransformer()
# 테스트 1: 기본 반복
test_prompt = "A. Paris\nB. London\n\nWhich city is the capital of France?"
result = transformer.transform(test_prompt, "claude-haiku")
print("=== Test 1: Basic Repetition ===")
print(f"Applied marker present: {transformer.config.applied_marker in result}")
print(f"Repeated: {test_prompt in result}")
print()
# 테스트 2: Position 패턴 (3회)
test_prompt_pos = "What item is in slot 25?"
result_pos = transformer.transform(test_prompt_pos, "gemini-flash")
repetitions = result_pos.count(test_prompt_pos)
print("=== Test 2: Position Pattern (3x) ===")
print(f"Repetitions: {repetitions}")
print()
# 테스트 3: CoT 스킵
test_prompt_cot = "Think step by step. What is 2+2?"
result_cot = transformer.transform(test_prompt_cot, "claude-haiku")
print("=== Test 3: CoT Skip ===")
print(f"Skipped (no change): {result_cot == test_prompt_cot}")
print()
# 테스트 4: 비대상 모델 스킵
test_prompt_skip = "What is the capital of France?"
result_skip = transformer.transform(test_prompt_skip, "claude-opus")
print("=== Test 4: Non-target Model Skip ===")
print(f"Skipped (no change): {result_skip == test_prompt_skip}")
Prompt Repetition — Evidence and Boundaries
Strongest evidence
- The main primary-source claim is the arXiv paper "Prompt Repetition Improves Non-Reasoning LLMs" (arXiv 2512.14982). Its abstract says that when not using reasoning, repeating the input prompt improves performance for Gemini, GPT, Claude, and DeepSeek models without increasing the number of generated tokens or latency.
- The paper is strongest evidence for non-reasoning use. Do not stretch it into a general claim about all prompting, all agent workflows, or all model classes.
What the evidence supports well
1. Long-context retrieval-like prompts where the question appears late. 2. Options-first multiple choice where the actual ask is easy to lose. 3. Position-sensitive / index-sensitive tasks where ordered details are easy to miss.
What the evidence does not support strongly
- blanket auto-application to every lightweight model request
- reasoning-heavy synthesis or planning work
- tool-heavy agent prompts with many policies/actions
- broad claims about NPC dialogue, creative writing, or general conversation quality
Why broader context work still matters
The broader prompt ecosystem keeps framing the real job as context engineering: improving what information the model sees and how it is arranged. See the Prompt Engineering Guide's Context Engineering Guide.
A related long-context paper explores emulating RAG through prompt engineering rather than merely duplicating the whole prompt, which reinforces that repetition is one option inside a larger design space (arXiv 2502.12462).
Practical boundary rule
Use prompt repetition when:
- the task is non-reasoning
- the failure is tied to late prompt information, option ordering, or index-heavy lookup
- the context budget still tolerates duplication
Do not use it when:
- the real problem is retrieval quality, source selection, or prompt bloat
- the model needs deeper reasoning rather than stronger late-context recall
- the prompt already sits near the context window limit
Prompt Repetition — Operator Checklist
Quick decision
Try repetition when all are true
- Model is non-reasoning or a lightweight / cheaper variant
- Failure looks like late-context miss, options-first confusion, or index-sensitive lookup
- Prompt still has enough context-window headroom for 2× or 3× input size
- You want a cheap A/B-style experiment before changing infrastructure
Route elsewhere when any are true
- Task needs multi-step reasoning or synthesis
- Retrieved context is noisy, contradictory, or incomplete
- Prompt already contains too many tools/policies/steps
- Context budget is tight enough that duplication risks truncation
- A simpler structural fix exists (move the question, trim context, add an example)
Safe intervention ladder
1. Repeat the question only 2. Repeat the full prompt 2× 3. Repeat the full prompt 3× only for index-sensitive cases with enough budget
Reporting template
- Fit: good / weak
- Task shape: long-context retrieval / options-first MCQ / position-sensitive lookup / other
- Smallest intervention: question only / full prompt 2× / full prompt 3× / do not use repetition
- Budget note: input-token impact and context-window risk
- Fallback: restructure prompt / retrieval / reasoning model / other
Example final line
This is a good fit for prompt repetition because the lightweight model is losing a late question after a long context block. Try repeating the question first or the full prompt 2× if budget allows; if that still fails, fix context selection or switch to a stronger reasoning model.
N:prompt-repetition
D:Decide when repeating a full prompt is a useful accuracy hack for non-reasoning or lightweight LLM tasks, and when the real fix is better prompt structure, retrieval, or a stronger model. Use for long-context retrieval, options-first MCQ, or position-sensitive prompts on Haiku/Flash/mini-class models — not as a universal default for reasoning-heavy or RAG-architecture problems.
T:Read|Write|Bash|Grep|Glob
G:prompt-engineering|llm-accuracy|long-context|lightweight-models|evaluation
U[6]:
**Long-context retrieval**: question comes after a large context block and gets lost
**Options-first MCQ**: choices appear before the actual ask
**Position-sensitive lookup**: inventory/index/ordered-list misses
**Lightweight models**: Haiku, Flash, mini-class non-reasoning runs
**Budget-aware experiments**: repeat question only, full prompt 2×, or bounded 3×
**Route-outs**: retrieval/context engineering, stronger reasoning models, prompt restructuring
F:Claude|Gemini|ChatGPT|Codex