[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
+153 -64
View File
@@ -2,91 +2,180 @@
id: wiki-2026-0508-reflection
title: Reflection
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-REFL-001]
aliases: [Self-Reflection, Reflexion, Programming Reflection]
duplicate_of: none
source_trust_level: A
confidence_score: 0.96
tags: [auto-reinforced, reflection, Self-Correction, metacognition, feedback-loop, ai-Reasoning]
confidence_score: 0.9
verification_status: applied
tags: [reflection, metaprogramming, llm, reflexion, self-critique]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: anthropic-sdk
---
# [[Reflection|Reflection]]
# Reflection
## 📌 한 줄 통찰 (The Karpathy Summary)
> "지능의 거울: 방금 행한 작업이나 내뱉은 답변에 오류는 없는지, 더 나은 방법은 없었는지 스스로 한발 물러나 검토함으로써, 고정된 성능을 넘어 실시간으로 자기 개선을 이뤄내는 '지각 있는 시스템'의 필수 기능."
## 한 줄
> **"매 program inspects itself, agent critiques itself"**. Reflection 은 dual concept — programming 에서 runtime 의 type/method introspection, AI 에서 LLM 의 self-critique loop. 2023 Reflexion paper (Shinn) 가 후자를 popularize, 2026 의 agent loop 의 backbone.
## 📖 구조화된 지식 (Synthesized Content)
리플렉션(Reflection) 혹은 자기 성찰은 지능 체계가 자신의 상태나 출력물을 스스로 분석하고 평가하는 과정입니다.
## 매 핵심
1. **AI에서의 구현 (Agentic Reflection)**:
* **Self-Critique**: "내 답변의 약점은 무엇인가?"라고 자문.
* **Error Detection**: 논리적 모순이나 팩트 체크 실패 감지. ([[Reliability|Reliability]]와 연결)
* **Adjustment**: 감지된 오류를 기반으로 재실행 계획 수립. (P-Reinforce의 기본 원리)
2. **왜 중요한가?**:
* 단발성 추론은 환각(Hallucination)에 취약하지만, 리플렉션 단계를 거친 지능은 비약적인 정확도와 신뢰성 향상을 보이기 때문임. (Metacognition과 연결)
### 매 Programming Reflection
- **Java**: `Class.forName`, `Method.invoke` — runtime type lookup.
- **Python**: `getattr`, `inspect`, `type()` — first-class.
- **Go**: `reflect.ValueOf`, `reflect.TypeOf` — verbose but explicit.
- **Rust**: 매 limited — `std::any::Any`, no runtime method dispatch.
- **Cost**: 매 10-100x slower than direct call. JIT 의 mitigates partially.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 외부의 정답 정책(Ground truth)에만 의존했으나, 현대 정책은 모델 내부의 지식들끼리 대조하여 모순 정책을 찾는 '내적 일관성 정책'을 통한 자가 성찰 정책이 가능해짐(RL Update).
- **정책 변화(RL Update)**: 단순 텍스트 성찰 정책을 넘어, 코드를 실행해 보고 에러가 나면 스스로 디버깅하는 '실행 결과 기반 성찰 정책'이 자율 에이전트의 핵심 기술 정책으로 자리 잡음. ([[Problem-Solving|Problem-Solving]]와 연결)
### 매 LLM Reflection
- **Reflexion (2023)**: agent generates → critiques → retries with verbal feedback in context.
- **Self-critique**: 매 model evaluates own output against rubric/spec.
- **Constitutional AI**: Anthropic 의 자기-revision against principles.
- **CRITIC (2024)**: tool-augmented self-correction.
- **Test-time compute (o1, Claude thinking)**: 매 internal reflection 의 productized.
## 🔗 지식 연결 (Graph)
- [[Reliability|Reliability]], [[P-Reinforce|P-Reinforce]], Metacognition, [[Problem-Solving|Problem-Solving]], [[Feedback-Loops|Feedback-Loops]]
- **Modern Tech/Tools**: Reflexion (Framework), Self-Correction algorithms, AI Debugging.
---
### 매 응용
1. Agent error recovery — failed tool call 의 self-diagnose.
2. Code generation — write → test → fix loop.
3. Math/logic — chain-of-thought + verifier.
4. Plugin systems — runtime method discovery.
5. ORM — entity-to-table reflection mapping.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Python introspection
```python
import inspect
**언제 쓰면 안 되는가:**
- *(TODO)*
class Service:
def fetch(self, url: str) -> dict: ...
def post(self, url: str, body: dict) -> None: ...
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
svc = Service()
for name, method in inspect.getmembers(svc, predicate=inspect.ismethod):
sig = inspect.signature(method)
print(f"{name}{sig}")
```
## 🤔 의사결정 기준 (Decision Criteria)
### Go reflect (struct tags)
```go
type User struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"email"`
}
**선택 A를 써야 할 때:**
- *(TODO)*
func validate(v any) error {
t := reflect.TypeOf(v)
val := reflect.ValueOf(v)
for i := 0; i < t.NumField(); i++ {
tag := t.Field(i).Tag.Get("validate")
if tag == "required" && val.Field(i).IsZero() {
return fmt.Errorf("%s required", t.Field(i).Name)
}
}
return nil
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Reflexion loop (Claude Opus 4.7)
```python
from anthropic import Anthropic
**기본값:**
> *(TODO)*
client = Anthropic()
MODEL = "claude-opus-4-7"
## ❌ 안티패턴 (Anti-Patterns)
def reflexion(task: str, max_iter: int = 3) -> str:
history = []
attempt = generate(task, history)
for i in range(max_iter):
critique = client.messages.create(
model=MODEL,
max_tokens=1024,
messages=[{
"role": "user",
"content": f"Task: {task}\nAttempt: {attempt}\n"
f"Critique: list errors, missing edge cases. "
f"If perfect, reply DONE."
}]
).content[0].text
if "DONE" in critique:
return attempt
history.append({"attempt": attempt, "critique": critique})
attempt = generate(task, history)
return attempt
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def generate(task: str, history: list) -> str:
ctx = "\n".join(f"Prev attempt: {h['attempt']}\nCritique: {h['critique']}"
for h in history)
resp = client.messages.create(
model=MODEL,
max_tokens=2048,
messages=[{"role": "user", "content": f"{ctx}\n\nTask: {task}"}]
)
return resp.content[0].text
```
### Self-critique with extended thinking
```python
# Claude Opus 4.7 의 native thinking — implicit reflection
resp = client.messages.create(
model="claude-opus-4-7",
max_tokens=8192,
thinking={"type": "enabled", "budget_tokens": 4096},
messages=[{"role": "user", "content": "Solve: ..."}]
)
# resp.content[0].type == "thinking" — reflection trace
# resp.content[1].type == "text" — final answer
```
### Plugin discovery (Java)
```java
ServiceLoader<Plugin> loader = ServiceLoader.load(Plugin.class);
for (Plugin p : loader) {
Method init = p.getClass().getMethod("init", Config.class);
init.invoke(p, cfg);
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Hot loop performance | 매 reflection X — codegen / direct call |
| Plugin / DI framework | Reflection OK (one-time init) |
| LLM agent error recovery | Reflexion loop (max 3 iter) |
| Math/code with verifier | Self-critique + tool execution |
| Chat UX | Extended thinking (native) |
**기본값**: 매 native thinking (Claude Opus 4.7) 의 first try, explicit Reflexion 의 verifiable domain (code/math).
## 🔗 Graph
- 부모: [[Metaprogramming]] · [[Agent-Architectures]]
- 변형: [[Reflexion]] · [[Constitutional-AI]] · [[Self-Consistency]]
- 응용: [[Plugin-Systems]] · [[Code-Generation]] · [[Tool-Use]]
- Adjacent: [[Chain-of-Thought]] · [[Extended-Thinking]] · [[ORM]]
## 🤖 LLM 활용
**언제**: 매 verifiable output (code passes tests, math 의 numerical), expensive failures (production agent), multi-step planning.
**언제 X**: simple Q&A (reflection 의 cost > benefit), creative generation (critique 의 collapse to mean), latency-critical (<500ms).
## ❌ 안티패턴
- **Infinite reflection**: 매 max_iter cap 없음 → cost runaway.
- **Critic = generator**: same model 의 critique 의 weak — 매 stronger verifier 의 use.
- **Reflection in hot path**: Java/Go 의 production code 의 reflect.Value 의 hide.
- **Verbal-only critique**: 매 numeric/test signal 없음 → noise.
- **Self-praise loop**: critique prompt 의 "find ANY issue" 의 biased.
## 🧪 검증 / 중복
- Verified (Reflexion paper 2023, Anthropic Constitutional AI, Java/Go reflect docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — programming + LLM reflection unified |