[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+240 -45
View File
@@ -2,73 +2,268 @@
id: wiki-2026-0508-iterative-prompting
title: Iterative Prompting
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [iterative prompting, refinement, self-refine, chain-of-verification, agent loop]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
verification_status: applied
tags: [llm, prompt-engineering, iterative, self-refine, cove, agent]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: Python
framework: LangChain / OpenAI / Anthropic
---
# [[Iterative Prompting|Iterative Prompting]]
# Iterative Prompting
## 📌 한 줄 통찰 (The Karpathy Summary)
Iterative Prompting(반복적 프롬프팅)은 완벽한 프롬프트를 한 번에 작성하는 대신, 단순하고 명확한 프롬프트로 시작하여 생성된 결과를 바탕으로 점진적으로 세부 사항을 수정해 나가는 기법이다 [1, 2]. 이는 단순한 지시어의 입력이 아니라 AI 모델과의 대화나 스케치 밑그림을 그리는 것과 같은 반복적인 협업 과정으로 간주된다 [1, 3, 4]. 창작자는 이 과정을 통해 조명, 구도, 스타일 등의 요소를 하나씩 변경하며 자신이 의도한 최종 시각적 결과물에 도달하게 된다 [1, 5, 6].
## 한 줄
> **"매 single prompt 의 X — 매 의 의 의 multiple round 의 의 의 quality ↑"**. 매 self-refine, CoVe (Chain-of-Verification), self-consistency, debate, agent loop. 매 modern: 매 reasoning model (o1, R1) 의 의 의 의 internal iteration. 매 trade-off: cost ↑, latency ↑.
## 📖 구조화된 지식 (Synthesized Content)
* **반복적 창작의 원리**
AI를 통한 이미지 생성은 단발성 행위가 아니라, 매우 짧은 시간으로 압축된 전통적인 미술 창작과 유사한 반복적 과정이다 [4, 7]. 일반적으로 첫 번째 프롬프트가 사용자의 의도를 약 80% 정도 달성하게 해주며, 이후의 반복을 통해 나머지 세부 사항을 다듬어 나가게 된다 [2]. 원하는 최종 결과물을 얻기 위해 보통 3~5번의 변형(variation) 이미지를 생성하는 것이 정상적이고 필수적인 과정으로 권장된다 [2, 5].
## 매 핵심
* **단계별 실행 워크플로우**
1. **단순한 시작**: 명확하지만 단순한 2~3문장의 기본 프롬프트나 다소 열려 있는 지시로 시작하여, AI의 초기 해석과 창의적 방향성을 확인한다 [1, 2, 8].
2. **결과 평가 및 결함 식별**: 생성된 결과물을 주의 깊게 검토하여 개선이 필요한 영역이나 반복적으로 나타나는 결함(defect)을 파악한다 [9-11].
3. **단계적 요소 수정**: 한 번에 조명, 구도, 스타일, 카메라 각도 등 단일 요소를 변경해가며 프롬프트를 수정하고 다시 생성하여, 해당 변화가 결과에 미치는 영향을 파악한다 [1, 5, 6].
4. **정교화 및 최적화**: 원치 않는 시각적 요소가 발생할 경우 이를 제거하기 위한 타겟화된 네거티브 프롬프트를 작성하거나, 더 상세한 지시를 추가하여 모델의 이해도를 높이고 불필요한 부분을 쳐낸다 [10-12].
### 매 patterns
- **Self-Refine** (Madaan 2023): 매 generate → critique → refine.
- **CoVe** (Dhuliawala 2023): 매 plan verification → check → refine.
- **Self-Consistency** (Wang 2022): 매 multiple sample → majority.
- **Debate** (Du 2023): 매 multi-LLM argue.
- **ReAct** (Yao 2022): 매 reason + act loop.
- **Reflexion** (Shinn 2023): 매 RL-style with verbal feedback.
* **플랫폼별 반복 활용 특징**
* **DALL-E 3**: ChatGPT의 언어 모델과 원활하게 통합되어 있어, 챗봇과의 대화형 상호작용을 통해 프롬프트를 반복적으로 개선(iterative refinement)하기에 매우 적합하다 [13].
* **전문 도구 (Midjourney, Stable Diffusion 등)**: 초기 생성 결과물을 베이스 이미지(Base Image)로 삼고, 이를 영역 변주(Vary Region)와 같은 인페인팅 도구나 시야 확장(Zoom Out) 등의 아웃페인팅 도구와 결합하여 점진적으로 수정해 나가는 전략이 프롬프트 엔지니어의 핵심 역량으로 꼽힌다 [4, 12].
### 매 응용
1. Math reasoning.
2. Code generation.
3. Long writing.
4. Fact verification.
5. Agent task.
## 🔗 지식 연결 (Graph)
- **Related Topics:** `[[Negative Prompts|Negative Prompts]]`, `[[인페인팅 (Inpainting)|Inpainting]]`, `[[Prompt Structure|Prompt Structure]]`
- **Projects/Contexts:** `[[AI Image Generation Workflow|AI Image Generation Workflow]]`
- **Contradictions/Notes:** 소스들은 공통적으로 처음부터 완벽하고 기술적인 긴 프롬프트를 작성하려는 시도를 피하고, 대신 단순하게 시작하여 의도적인 반복(iterate deliberately) 과정을 통해 다음 프롬프트를 작성하는 법을 배우라고 강조한다 [1, 14].
## 💻 패턴
---
*Last updated: 2026-04-30*
### Self-refine (Madaan)
```python
def self_refine(prompt, llm, max_iter=3):
output = llm.generate(prompt)
for _ in range(max_iter):
critique = llm.generate(f"""Critique this output:
{output}
List specific issues. If perfect, say 'DONE'.""")
if 'DONE' in critique: return output
output = llm.generate(f"""Original: {prompt}
Previous output: {output}
Critique: {critique}
Improved output:""")
return output
```
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Chain-of-Verification (CoVe)
```python
def cove(question, llm):
# 매 1. Initial answer
initial = llm.generate(f'Answer: {question}')
# 매 2. Plan verification questions
verify_qs = llm.generate(f"""Generate verification questions for:
{initial}
List as numbered questions.""").split('\n')
# 매 3. Answer each independently (avoid bias)
verifications = [llm.generate(f'Answer: {q}') for q in verify_qs if q.strip()]
# 매 4. Refine
return llm.generate(f"""Original: {initial}
Verifications: {verifications}
Refined answer accounting for any inconsistencies:""")
```
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Self-consistency
```python
def self_consistency(question, llm, n=10):
"""매 sample N times, majority vote."""
answers = [llm.generate(question, temperature=0.7) for _ in range(n)]
extracted = [extract_answer(a) for a in answers]
from collections import Counter
return Counter(extracted).most_common(1)[0][0]
```
**언제 쓰면 안 되는가:**
- *(TODO)*
### Multi-agent debate
```python
def debate(question, agents, n_rounds=3):
answers = {a.name: a.generate(question) for a in agents}
for r in range(n_rounds):
for a in agents:
others = '\n'.join(f'{n}: {ans}' for n, ans in answers.items() if n != a.name)
answers[a.name] = a.generate(f"""Question: {question}
Other agents:
{others}
Refine your answer (or stick if confident):""")
return answers
```
## 🧪 검증 상태 (Validation)
### ReAct (reason + act)
```python
def react(task, llm, tools):
history = [f'Task: {task}']
for _ in range(10):
thought = llm.generate('\n'.join(history) + '\nThought:')
history.append(f'Thought: {thought}')
if 'final answer' in thought.lower():
return thought
action = llm.generate('\n'.join(history) + '\nAction:')
observation = execute(action, tools)
history.append(f'Action: {action}\nObservation: {observation}')
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Reflexion (verbal RL)
```python
def reflexion(task, llm, tools, max_attempts=5):
memory = []
for attempt in range(max_attempts):
result = react_with_memory(task, llm, tools, memory)
success = evaluate(result)
if success: return result
# 매 reflect
reflection = llm.generate(f"""Task: {task}
Attempt {attempt}: {result}
What went wrong? What should I try differently?""")
memory.append(reflection)
return result
```
## 🧬 중복 검사 (Duplicate Check)
### Iterative refinement (writing)
```python
def iterative_writing(topic, llm, draft_iterations=3):
draft = llm.generate(f'Outline: {topic}')
for _ in range(draft_iterations):
feedback = llm.generate(f"""Critique:
- Clarity (1-10)
- Argument strength (1-10)
- Specific issues
{draft}""")
draft = llm.generate(f"""Revise based on feedback:
{feedback}
Original:
{draft}""")
return draft
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Self-correction (math)
```python
def self_correct_math(problem, llm):
answer = llm.generate(f'Solve step by step: {problem}')
# 매 verify
check = llm.generate(f"""Check this solution:
{answer}
Verify each step. If error, point it out.""")
if 'error' in check.lower():
answer = llm.generate(f"""Original: {answer}
Check: {check}
Corrected solution:""")
return answer
```
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
### Best-of-N + judge
```python
def best_of_n(prompt, llm, judge_llm, n=8):
candidates = [llm.generate(prompt, temperature=0.7) for _ in range(n)]
judge_prompt = f"""Pick best answer.
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
Candidates:
{format_candidates(candidates)}
## 🕓 변경 이력 (Changelog)
Output just the index."""
best_idx = int(judge_llm.generate(judge_prompt))
return candidates[best_idx]
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Tree-of-Thoughts (ToT)
```python
def tree_of_thoughts(problem, llm, branching=3, depth=4):
"""매 매 step 의 의 의 multiple thoughts → 매 best."""
paths = [[]]
for _ in range(depth):
new_paths = []
for path in paths:
thoughts = [llm.generate(f'{problem}\nPath: {path}\nNext thought:') for _ in range(branching)]
for t in thoughts:
new_paths.append(path + [t])
# 매 score + prune
scored = [(score(p, problem, llm), p) for p in new_paths]
paths = [p for _, p in sorted(scored, key=lambda x: -x[0])[:branching]]
return paths[0]
```
### Cost monitoring
```python
def cost_aware_iterate(prompt, llm, budget_tokens):
used = 0
output = llm.generate(prompt)
used += llm.last_usage.total_tokens
while used < budget_tokens:
critique = llm.generate(f'Critique: {output}')
used += llm.last_usage.total_tokens
if 'DONE' in critique or used > budget_tokens * 0.9: return output
output = llm.generate(f'Refine: {output} {critique}')
used += llm.last_usage.total_tokens
return output
```
### Stop criterion (auto)
```python
def auto_stop_iterate(prompt, llm, max_iter=5):
prev = llm.generate(prompt)
for _ in range(max_iter):
new = llm.generate(f'Improve: {prev}')
if similarity(prev, new) > 0.95: return new # 매 converged
prev = new
return prev
```
## 매 결정 기준
| 상황 | Pattern |
|---|---|
| Math / reasoning | Self-consistency / CoVe |
| Code | Self-refine + execute check |
| Writing | Iterative refinement |
| Open-ended | Best-of-N + judge |
| Agent task | ReAct / Reflexion |
| Complex search | Tree-of-Thoughts |
**기본값**: 매 reasoning = self-consistency (cheap) + CoVe (verify). 매 agent = ReAct + Reflexion. 매 cost-aware budget cap.
## 🔗 Graph
- 부모: [[Prompt-Engineering]] · [[LLM-Reasoning]]
- 변형: [[Self-Refine]] · [[Chain-of-Verification]] · [[ReAct]] · [[Reflexion]] · [[Tree-of-Thoughts]]
- 응용: [[Hallucination-in-LLMs]] · [[GRPO]] · [[Foundation-Models]]
- Adjacent: [[Best-of-N_Sampling]] · [[Self-Consistency]]
## 🤖 LLM 활용
**언제**: 매 reasoning. 매 high-stakes. 매 agent.
**언제 X**: 매 simple completion (cost waste).
## ❌ 안티패턴
- **No stop criterion**: 매 infinite loop.
- **No cost budget**: 매 bill shock.
- **Same prompt every iter**: 매 no progress.
- **No diverse sampling** (self-consistency): 매 same answer.
- **Skip judge**: 매 best-of-N 매 useless.
## 🧪 검증 / 중복
- Verified (Madaan Self-Refine 2023, Dhuliawala CoVe 2023, Wang Self-Consistency 2022, Yao ReAct/ToT, Shinn Reflexion 2023).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — patterns + 매 self-refine / CoVe / ReAct / Reflexion / ToT code |