[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,109 +1,147 @@
|
||||
---
|
||||
id: wiki-2026-0508-e-component-execution-loop
|
||||
title: E component (Execution Loop)
|
||||
title: E-component (Execution Loop)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Execution Loop, E-Loop, Agent Runtime Loop]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [agent, runtime, llm, architecture]
|
||||
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: unspecified
|
||||
framework: unspecified
|
||||
language: Python
|
||||
framework: anthropic-sdk
|
||||
---
|
||||
|
||||
# [[E-component (Execution Loop)|E-component (Execution Loop)]]
|
||||
# E-component (Execution Loop)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
E-component(Execution Loop)는 에이전트 하네스의 '심장'에 해당하는 구성 요소로, 에이전트가 목표를 달성할 때까지 수행하는 **관찰(Observe) - 사고(Think) - 행동(Act)** 루프를 제어하고 관리한다. 에이전트의 생명 주기를 유지하며, 언제 모델을 호출하고 언제 도구를 실행할지, 그리고 작업이 완료되었는지를 판단하는 결정론적(Deterministic) 흐름 제어 계층이다.
|
||||
## 매 한 줄
|
||||
> **"매 LLM agent 의 heartbeat"**. 매 EST (Execution / State / Tools) component triad 의 E — 매 model-call → 매 tool-dispatch → 매 result-feedback 의 inner loop. 매 Claude Agent SDK / OpenAI Assistants / LangGraph 매 same primitive.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **루프 제어 전략**:
|
||||
* **고정 반복 (Fixed Iteration)**: 사전에 정의된 횟수만큼 루프를 실행.
|
||||
* **조건 기반 종료 (Condition-based)**: 모델이 "완료" 신호를 보내거나, 특정 결과값에 도달했을 때 종료.
|
||||
* **자기 반성 (Self-Correction)**: 루프 내부에서 이전 행동의 결과를 평가하고 다음 행동을 수정하는 단계(Reflexion)를 포함.
|
||||
* **상태 전이 관리 (State Transition)**: 루프의 각 단계에서 에이전트의 내부 상태가 어떻게 변하는지 추적하며, 오류 발생 시 이전 상태로 복구(Rollback)하거나 재시도(Retry)하는 로직을 수행한다.
|
||||
* **비동기 작업 관리**: 장시간 실행되는 도구나 외부 API 호출 시 루프가 멈추지 않도록 비동기 스트리밍과 이벤트 대기 메커니즘을 관리한다.
|
||||
* **휴먼-인-더-루프 (HITL) 개입**: 루프의 특정 지점에서 인간의 승인을 기다리거나 피드백을 받아 작업 방향을 수정하는 중단점(Breakpoints)을 제어한다.
|
||||
* **토큰 및 비용 가드레일**: 무한 루프에 빠져 토큰을 과도하게 소모하는 것을 방지하기 위해 최대 실행 시간이나 비용 한도를 강제한다.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **루프 깊이와 정확도**: 루프를 많이 돌수록 결과의 품질은 향상될 수 있으나(Test-time scaling), 지연 시간과 비용이 비례해서 증가한다.
|
||||
* **무한 루프 리스크**: 모델이 동일한 잘못된 행동을 반복하며 루프를 탈출하지 못하는 '논리적 데드락'에 빠질 수 있다.
|
||||
* **상태 폭발**: 루프가 길어질수록 컨텍스트에 쌓이는 데이터가 많아져 모델의 성능이 저하(Context Rot)될 수 있다.
|
||||
### 매 mechanism
|
||||
1. Send messages + tool definitions to LLM.
|
||||
2. LLM 매 returns text + (optional) tool_use blocks.
|
||||
3. If tool_use: dispatch to T-component (Tool Registry), append tool_result to state.
|
||||
4. Loop until 매 stop_reason == "end_turn" or max_iterations.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
### Related Concepts
|
||||
* [[Agent Harness|Agent Harness]]
|
||||
* 연결 이유: E-component는 하네스의 실행 주체이다.
|
||||
* [[C-component (Context Manager)|C-component (Context Manager)]]
|
||||
* 연결 이유: 루프가 한 번 돌 때마다 C-component가 갱신된 컨텍스트를 공급해야 한다.
|
||||
* [[Self-verification|Self-verification]]
|
||||
* 연결 이유: E-component 내에서 결과의 신뢰성을 검증하는 핵심 기법이다.
|
||||
### 매 components
|
||||
- **E (this)**: orchestrator — message-pump.
|
||||
- **S** (State Store): conversation history, scratch state.
|
||||
- **T** (Tool Registry): handler dispatch, schema validation.
|
||||
|
||||
### Deeper Research Questions
|
||||
* 에이전트가 작업의 '난이도'를 스스로 평가하여 루프의 복잡도를 동적으로 조절하는 스케줄링 알고리즘은 무엇인가?
|
||||
* 다중 에이전트 협업 시, 여러 에이전트의 개별 실행 루프를 하나의 상위 루프(Orchestration Loop)로 통합하는 효율적인 방법은 무엇인가?
|
||||
* 루프 실행 중 발생하는 중간 산출물(Intermediate thoughts) 중 어떤 정보가 최종 결과 도달에 결정적이었는지를 분석하여 향후 루프를 최적화하는 기법은 무엇인가?
|
||||
### 매 응용
|
||||
1. Code agents (Claude Code, Cursor, Devin).
|
||||
2. Research agents (Perplexity, Deep Research).
|
||||
3. Workflow automation.
|
||||
|
||||
### Practical Application Contexts
|
||||
* **Implementation:** `while` 루프 내에서 `agent.think()`와 `agent.act()`를 호출하고, 각 단계의 결과를 `AgentHistory`에 기록하는 구조로 구현한다.
|
||||
* **System Design:** 웹 서비스 환경에서 에이전트 실행 루프를 백그라운드 작업(Celery, Redis 등)으로 처리하여 사용자의 연결이 끊겨도 작업이 완료되도록 설계한다.
|
||||
## 💻 패턴
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-01*
|
||||
### Minimal execution loop (Anthropic SDK 2026)
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
client = Anthropic()
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (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
|
||||
def run(messages, tools, dispatch, max_iters=20):
|
||||
for _ in range(max_iters):
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4096,
|
||||
tools=tools,
|
||||
messages=messages,
|
||||
)
|
||||
messages.append({"role": "assistant", "content": resp.content})
|
||||
if resp.stop_reason == "end_turn":
|
||||
return resp
|
||||
tool_results = [
|
||||
{"type": "tool_result", "tool_use_id": b.id, "content": dispatch(b.name, b.input)}
|
||||
for b in resp.content if b.type == "tool_use"
|
||||
]
|
||||
messages.append({"role": "user", "content": tool_results})
|
||||
raise RuntimeError("max iterations exceeded")
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Streaming variant
|
||||
```python
|
||||
with client.messages.stream(model="claude-opus-4-7", messages=messages, tools=tools) as stream:
|
||||
for event in stream:
|
||||
if event.type == "content_block_delta":
|
||||
print(event.delta.text, end="", flush=True)
|
||||
final = stream.get_final_message()
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Tool dispatch (T-component plug-in)
|
||||
```python
|
||||
TOOLS = {
|
||||
"read_file": lambda input: open(input["path"]).read(),
|
||||
"list_dir": lambda input: os.listdir(input["path"]),
|
||||
}
|
||||
def dispatch(name, input):
|
||||
try: return TOOLS[name](input)
|
||||
except Exception as e: return f"Error: {e}"
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Stop conditions
|
||||
```python
|
||||
STOP = {"end_turn", "stop_sequence", "max_tokens"}
|
||||
if resp.stop_reason in STOP: break
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Prompt caching the system + tools
|
||||
```python
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
system=[{"type": "text", "text": SYSTEM, "cache_control": {"type": "ephemeral"}}],
|
||||
tools=[{**t, "cache_control": {"type": "ephemeral"}} for t in tools],
|
||||
messages=messages,
|
||||
)
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Budget guard
|
||||
```python
|
||||
total_tokens = 0
|
||||
while True:
|
||||
resp = client.messages.create(...)
|
||||
total_tokens += resp.usage.input_tokens + resp.usage.output_tokens
|
||||
if total_tokens > BUDGET: raise BudgetExceeded()
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Single-turn task | Direct API call |
|
||||
| Multi-tool task | E-loop |
|
||||
| Long-running workflow | E-loop + checkpointing (S) |
|
||||
|
||||
**기본값**: E-loop + prompt caching + budget guard + max-iter clamp.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Agent-Architecture]]
|
||||
- 변형: [[ReAct]] · [[Plan-and-Execute]]
|
||||
- 응용: [[Claude-Agent-SDK]] · [[LangGraph]]
|
||||
- Adjacent: [[S-component-State-Store]] · [[T-component-Tool-Registry]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: building agent runtime, multi-step tool-use task.
|
||||
**언제 X**: pure single-shot prompt (no tools, no state).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No max-iter cap**: 매 infinite-loop 의 risk.
|
||||
- **No budget guard**: 매 unbounded cost.
|
||||
- **Recreating system prompt per turn**: cache miss → 매 5-10x cost.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Anthropic Messages API docs, Claude Agent SDK).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — E-component FULL with SDK 2026 loop patterns |
|
||||
|
||||
Reference in New Issue
Block a user