[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -0,0 +1,185 @@
|
||||
---
|
||||
id: ai-agentic-patterns
|
||||
title: Agentic Patterns — Plan / Reflect / Multi-agent
|
||||
category: Coding
|
||||
status: draft
|
||||
source_trust_level: B
|
||||
verification_status: conceptual
|
||||
created_at: 2026-05-09
|
||||
updated_at: 2026-05-09
|
||||
tags: [ai, agent, agentic, vibe-coding]
|
||||
tech_stack: { language: "TS / LLM", applicable_to: ["Backend"] }
|
||||
applied_in: []
|
||||
aliases: [agent, ReAct, Reflexion, multi-agent, planner, supervisor, swarm]
|
||||
---
|
||||
|
||||
# Agentic Patterns
|
||||
|
||||
> Tool 호출 + 추론을 묶은 자율 시스템. **Plan → Execute → Reflect** loop. Multi-agent (각 역할별) 가 복잡 작업에 강력. 단 비용 / 신뢰성 / 안전성 = 새 도전.
|
||||
|
||||
## 📖 핵심 개념
|
||||
- ReAct: Reasoning + Acting 인터리브 (위 function calling 의 기본).
|
||||
- Plan-and-Execute: 먼저 계획 세움 → 실행.
|
||||
- Reflection: 결과 자체 평가 → 재시도.
|
||||
- Multi-agent: 역할별 (planner / coder / reviewer).
|
||||
|
||||
## 💻 코드 패턴
|
||||
|
||||
### Plan-and-Execute
|
||||
```ts
|
||||
async function planAndExecute(task: string) {
|
||||
// 1. Plan
|
||||
const plan = await llm.complete({
|
||||
system: 'Decompose into 3-7 numbered steps. Output JSON: {"steps":[...]}.',
|
||||
user: task,
|
||||
response_format: { type: 'json_object' },
|
||||
});
|
||||
const steps = JSON.parse(plan).steps as string[];
|
||||
|
||||
// 2. Execute
|
||||
const results: string[] = [];
|
||||
for (const step of steps) {
|
||||
const r = await agentLoop(step + `\n\nContext from previous: ${results.join('\n')}`);
|
||||
results.push(r);
|
||||
}
|
||||
|
||||
// 3. Synthesize
|
||||
return llm.complete({
|
||||
system: 'Synthesize the results.',
|
||||
user: `Task: ${task}\n\nResults:\n${results.map((r, i) => `Step ${i + 1}: ${r}`).join('\n')}`,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Reflection (자체 평가)
|
||||
```ts
|
||||
async function reflectiveAgent(task: string, maxAttempts = 3) {
|
||||
let result: string | null = null;
|
||||
for (let i = 0; i < maxAttempts; i++) {
|
||||
result = await agentLoop(task + (i > 0 ? `\n\nPrevious attempt critique: ${critique}` : ''));
|
||||
|
||||
const critique = await llm.complete({
|
||||
system: 'Evaluate the answer. If perfect, output "OK". Otherwise, point out specific issues.',
|
||||
user: `Task: ${task}\nAnswer: ${result}`,
|
||||
});
|
||||
|
||||
if (critique.startsWith('OK')) return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
### Multi-agent (Planner + Worker)
|
||||
```ts
|
||||
async function multiAgent(task: string) {
|
||||
const planner = createAgent({
|
||||
system: 'You decompose tasks. Output JSON tasks for workers.',
|
||||
tools: [],
|
||||
});
|
||||
|
||||
const coder = createAgent({
|
||||
system: 'You write code.',
|
||||
tools: [readFile, writeFile, runTest],
|
||||
});
|
||||
|
||||
const reviewer = createAgent({
|
||||
system: 'You review code for bugs and style.',
|
||||
tools: [readFile],
|
||||
});
|
||||
|
||||
const tasks = JSON.parse(await planner.run(task));
|
||||
for (const t of tasks) {
|
||||
const code = await coder.run(t);
|
||||
const review = await reviewer.run(code);
|
||||
if (review.includes('LGTM')) continue;
|
||||
await coder.run(`Fix issues: ${review}`); // refine
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Supervisor / Worker (LangGraph 스타일)
|
||||
```ts
|
||||
type State = { task: string; messages: Message[]; nextAgent: 'coder' | 'reviewer' | 'done' };
|
||||
|
||||
async function supervisor(state: State): Promise<State> {
|
||||
const decision = await llm.complete({
|
||||
system: 'Decide next: coder, reviewer, or done.',
|
||||
user: JSON.stringify(state),
|
||||
});
|
||||
return { ...state, nextAgent: parseDecision(decision) };
|
||||
}
|
||||
|
||||
async function graph(initial: State): Promise<State> {
|
||||
let state = initial;
|
||||
while (state.nextAgent !== 'done') {
|
||||
state = await supervisor(state);
|
||||
if (state.nextAgent === 'coder') state = await coderNode(state);
|
||||
if (state.nextAgent === 'reviewer') state = await reviewerNode(state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
```
|
||||
|
||||
### Memory (단순)
|
||||
```ts
|
||||
class AgentMemory {
|
||||
private notes: { ts: number; content: string }[] = [];
|
||||
add(c: string) { this.notes.push({ ts: Date.now(), content: c }); }
|
||||
recent(n = 10) { return this.notes.slice(-n).map(x => x.content).join('\n'); }
|
||||
}
|
||||
```
|
||||
|
||||
복잡 = vector DB + retrieval.
|
||||
|
||||
### 안전 가드 (guardrails)
|
||||
```ts
|
||||
async function safeExecute(plan: Step) {
|
||||
// High-risk: 사용자 confirm
|
||||
if (plan.action === 'delete_file' || plan.action === 'send_email') {
|
||||
const ok = await askUser(`Confirm: ${plan.summary}`);
|
||||
if (!ok) return { skipped: true };
|
||||
}
|
||||
return await execute(plan);
|
||||
}
|
||||
```
|
||||
|
||||
### Cost / iteration cap
|
||||
```ts
|
||||
class Budget {
|
||||
constructor(private maxTokens: number, private maxIters: number) {}
|
||||
used = { tokens: 0, iters: 0 };
|
||||
check() {
|
||||
if (this.used.tokens > this.maxTokens) throw new Error('budget exceeded');
|
||||
if (this.used.iters > this.maxIters) throw new Error('iter limit');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준
|
||||
| 작업 | 패턴 |
|
||||
|---|---|
|
||||
| 1-2 step | 단순 tool loop |
|
||||
| 멀티 step + 반복 | Plan-and-Execute |
|
||||
| 정확성 critical | Reflection |
|
||||
| 복잡 도메인 (코딩, 조사) | Multi-agent |
|
||||
| Long-running (시간 단위) | Temporal / Durable agents |
|
||||
| 사용자 in-the-loop | 중간 confirm |
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **무한 loop 가능성**: max iters / max tokens / max time.
|
||||
- **High-stakes action 자동**: 결제 / 삭제 / 메일은 confirm.
|
||||
- **Memory 없이 long task**: context 잃음.
|
||||
- **Agent 가 외부 prompt injection 따름**: system 권위 명시 + sanitize.
|
||||
- **1 LLM 모든 역할**: 너무 큰 prompt + 혼란. 분리.
|
||||
- **Reflection 무한**: 같은 결과 반복 — limit.
|
||||
- **Cost 추적 없음**: 1 task 가 $10 — 알아채기 늦음.
|
||||
|
||||
## 🤖 LLM 활용 힌트
|
||||
- Plan + tool loop + reflection + budget 4종.
|
||||
- Multi-agent = 역할별 분리.
|
||||
- Guardrail (HITL) 항상 있어야.
|
||||
|
||||
## 🔗 관련 문서
|
||||
- [[AI_Function_Calling_Deep]]
|
||||
- [[AI_Prompt_Engineering_Patterns]]
|
||||
- [[AI_LLM_Eval_Patterns]]
|
||||
Reference in New Issue
Block a user