---
id: wiki-2026-0508-reflection
title: Reflection
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Self-Reflection, Reflexion, Programming Reflection]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [reflection, metaprogramming, llm, reflexion, self-critique]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: python
  framework: anthropic-sdk
---

# Reflection

## 매 한 줄
> **"매 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.

## 매 핵심

### 매 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.

### 매 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.

### 매 응용
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.

## 💻 패턴

### Python introspection
```python
import inspect

class Service:
    def fetch(self, url: str) -> dict: ...
    def post(self, url: str, body: dict) -> None: ...

svc = Service()
for name, method in inspect.getmembers(svc, predicate=inspect.ismethod):
    sig = inspect.signature(method)
    print(f"{name}{sig}")
```

### Go reflect (struct tags)
```go
type User struct {
    Name  string `json:"name" validate:"required"`
    Email string `json:"email" validate:"email"`
}

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
}
```

### Reflexion loop (Claude Opus 4.7)
```python
from anthropic import Anthropic

client = Anthropic()
MODEL = "claude-opus-4-7"

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

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]]
- 변형: [[Reflexion]] · [[AI_Safety_and_Alignment|Constitutional-AI]] · [[Self-Consistency]]
- 응용: [[Code-Generation]] · [[Tool-Use]]
- Adjacent: [[Chain-of-Thought]]

## 🤖 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 |
