hee_!J commited on
Commit
5a68bbf
·
1 Parent(s): 812ab59

feat(experiments): workflow vs agentic 정량 비교 (LLM/tool/cost/latency/인용 깊이)

Browse files
experiments/agentic_vs_workflow/__init__.py ADDED
File without changes
experiments/agentic_vs_workflow/benchmark.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Workflow vs Agentic 비교 실험
2
+
3
+ 같은 알람(A1·A2·A3)에 대해 두 패턴을 실행하고 정량 비교:
4
+ - **Workflow**: Tier 2/3/4 각 1회 LLM 호출, 사전 RAG 1회 (이전 코드 그대로 인라인 재현)
5
+ - **Agentic**: tool-using agent (현재 main 코드, agents/*.py)
6
+
7
+ 측정:
8
+ - 호출 횟수: LLM calls, tool calls (per tier, per alarm)
9
+ - 다양성: 사용한 도구 유니크 수, 인용 문서 유니크 수
10
+ - 시간: per-tier latency, total
11
+ - 비용: 추정 토큰·USD (gpt-5-mini 단가 기준)
12
+ - 품질: 인용된 citation 수 (얕은 grounding vs 깊은 grounding)
13
+
14
+ 차트 3종: 호출 횟수 / latency / 인용 깊이 (matplotlib)
15
+
16
+ 실행: python -m experiments.agentic_vs_workflow.benchmark
17
+ 결과: results.md + charts/*.png
18
+ """
19
+ import json
20
+ import time
21
+ from pathlib import Path
22
+
23
+ import matplotlib.pyplot as plt
24
+ import numpy as np
25
+
26
+ from agents.cause import run_cause as agentic_cause
27
+ from agents.detection import run_detection
28
+ from agents.impact import run_impact as agentic_impact
29
+ from agents.llm import SUBAGENT_MODEL, client
30
+ from agents.rag.store import load_document, search
31
+ from agents.response import run_response as agentic_response
32
+ from core.schema import Tier1, Tier2, Tier3, Tier4
33
+ from data.demo import DEFAULT_ALARMS
34
+ from data.wip import get_affected_wip
35
+
36
+ plt.rcParams["font.family"] = ["Apple SD Gothic Neo", "AppleGothic", "DejaVu Sans"]
37
+ plt.rcParams["axes.unicode_minus"] = False
38
+
39
+ OUT_DIR = Path(__file__).parent
40
+ CHART_DIR = OUT_DIR / "charts"
41
+ ALARMS = ["A1", "A2", "A3"]
42
+ TOP_K = 3
43
+
44
+ # gpt-5-mini 추정 단가 (USD per 1M token, 2026 기준 가정)
45
+ PRICE_INPUT = 0.25
46
+ PRICE_OUTPUT = 2.0
47
+
48
+
49
+ # ==================== Workflow 버전 (이전 단일 호출 방식 재현) ====================
50
+
51
+ _T2_SCHEMA = {
52
+ "type": "object",
53
+ "properties": {
54
+ "causes": {
55
+ "type": "array",
56
+ "items": {
57
+ "type": "object",
58
+ "properties": {
59
+ "name": {"type": "string"},
60
+ "pct": {"type": "integer"},
61
+ "evidence": {"type": "string"},
62
+ "citations": {"type": "array", "items": {"type": "string"}},
63
+ },
64
+ "required": ["name", "pct", "evidence", "citations"],
65
+ "additionalProperties": False,
66
+ },
67
+ }
68
+ },
69
+ "required": ["causes"],
70
+ "additionalProperties": False,
71
+ }
72
+
73
+ _T3_SCHEMA = {
74
+ "type": "object",
75
+ "properties": {
76
+ "yield_loss": {"type": "number"},
77
+ "downstream_dependencies": {
78
+ "type": "array",
79
+ "items": {
80
+ "type": "object",
81
+ "properties": {
82
+ "stage": {"type": "string"},
83
+ "delta": {"type": "string"},
84
+ "tag": {"type": "string"},
85
+ "kind": {"type": "string", "enum": ["impacted", "minor"]},
86
+ },
87
+ "required": ["stage", "delta", "tag", "kind"],
88
+ "additionalProperties": False,
89
+ },
90
+ },
91
+ },
92
+ "required": ["yield_loss", "downstream_dependencies"],
93
+ "additionalProperties": False,
94
+ }
95
+
96
+ _T4_SCHEMA = {
97
+ "type": "object",
98
+ "properties": {
99
+ "immediate": {
100
+ "type": "array",
101
+ "items": {
102
+ "type": "object",
103
+ "properties": {
104
+ "text": {"type": "string"},
105
+ "meta": {"type": ["string", "null"]},
106
+ },
107
+ "required": ["text", "meta"],
108
+ "additionalProperties": False,
109
+ },
110
+ },
111
+ "longterm": {
112
+ "type": "array",
113
+ "items": {
114
+ "type": "object",
115
+ "properties": {
116
+ "text": {"type": "string"},
117
+ "meta": {"type": ["string", "null"]},
118
+ },
119
+ "required": ["text", "meta"],
120
+ "additionalProperties": False,
121
+ },
122
+ },
123
+ },
124
+ "required": ["immediate", "longterm"],
125
+ "additionalProperties": False,
126
+ }
127
+
128
+
129
+ def _llm_call(messages, schema, name):
130
+ return client().chat.completions.create(
131
+ model=SUBAGENT_MODEL,
132
+ messages=messages,
133
+ response_format={"type": "json_schema", "json_schema": {"name": name, "schema": schema, "strict": True}},
134
+ )
135
+
136
+
137
+ def workflow_run_cause(alarm: dict, tier1: Tier1, trace: dict) -> Tier2:
138
+ sensors = ", ".join(f["name"] for f in tier1["features"])
139
+ query = f"{alarm['title']} {alarm.get('feature') or ''} {sensors} 원인 분석"
140
+ doc_ids = search(query, top_k=TOP_K)
141
+ knowledge = "\n\n".join(f"[{d}]\n{load_document(d)}" for d in doc_ids)
142
+ user = f"""## 이상 알람
143
+ - 공정: {alarm['title']}, lot: {alarm['lot_id']}
144
+ ## Tier 1
145
+ - 점수: {tier1['score']}, 센서: {sensors}
146
+ ## 사내 지식 문서
147
+ {knowledge}
148
+ 위 정보로 원인 2~3개를 산출."""
149
+ resp = _llm_call(
150
+ [
151
+ {"role": "system", "content": "반도체 공정 ��인 분석 전문가. JSON 스키마에 맞춰 응답."},
152
+ {"role": "user", "content": user},
153
+ ],
154
+ _T2_SCHEMA,
155
+ "tier2",
156
+ )
157
+ trace["llm_calls"] = 1
158
+ trace["tool_calls"] = 0
159
+ trace["unique_tools"] = 0
160
+ trace["input_tokens"] = resp.usage.prompt_tokens
161
+ trace["output_tokens"] = resp.usage.completion_tokens
162
+ return json.loads(resp.choices[0].message.content)
163
+
164
+
165
+ def workflow_run_impact(alarm: dict, tier1: Tier1, tier2: Tier2, trace: dict) -> Tier3:
166
+ cause_names = " ".join(c["name"] for c in tier2["causes"])
167
+ query = f"{alarm['title']} 하류 후공정 영향 수율 {cause_names}"
168
+ doc_ids = search(query, top_k=TOP_K)
169
+ knowledge = "\n\n".join(f"[{d}]\n{load_document(d)}" for d in doc_ids)
170
+ cause_lines = "\n".join(f"- {c['name']} ({c['pct']}%)" for c in tier2["causes"])
171
+ user = f"""## 알람: {alarm['title']}
172
+ ## 원인
173
+ {cause_lines}
174
+ ## 사내 지식
175
+ {knowledge}
176
+ yield_loss와 downstream_dependencies 산출."""
177
+ resp = _llm_call(
178
+ [
179
+ {"role": "system", "content": "반도체 영향 평가 전문가. JSON 스키마에 맞춰 응답."},
180
+ {"role": "user", "content": user},
181
+ ],
182
+ _T3_SCHEMA,
183
+ "tier3_part",
184
+ )
185
+ trace["llm_calls"] = 1
186
+ trace["tool_calls"] = 0
187
+ trace["unique_tools"] = 0
188
+ trace["input_tokens"] = resp.usage.prompt_tokens
189
+ trace["output_tokens"] = resp.usage.completion_tokens
190
+ llm_out = json.loads(resp.choices[0].message.content)
191
+ current = {"stage": alarm["title"].split()[0], "delta": f"+{tier1['score']}", "tag": "현재", "kind": "current"}
192
+ return {
193
+ "yield_loss": round(float(llm_out["yield_loss"]), 1),
194
+ "dependencies": [current] + llm_out["downstream_dependencies"],
195
+ "impact_lots": get_affected_wip(alarm["id"]),
196
+ }
197
+
198
+
199
+ def workflow_run_response(alarm: dict, tier1: Tier1, tier2: Tier2, tier3: Tier3, trace: dict) -> Tier4:
200
+ causes = " ".join(c["name"] for c in tier2["causes"])
201
+ query = f"{alarm['title']} 대응 PM 조치 보류 모니터링 {causes}"
202
+ doc_ids = search(query, top_k=4)
203
+ knowledge = "\n\n".join(f"[{d}]\n{load_document(d)}" for d in doc_ids)
204
+ cause_lines = "\n".join(f"- {c['name']} ({c['pct']}%)" for c in tier2["causes"])
205
+ user = f"""## 알람: {alarm['title']}
206
+ ## 원인
207
+ {cause_lines}
208
+ ## 영향
209
+ - yield_loss: {tier3['yield_loss']}%p
210
+ ## 사내 지식
211
+ {knowledge}
212
+ immediate와 longterm 조치 권고."""
213
+ resp = _llm_call(
214
+ [
215
+ {"role": "system", "content": "반도체 대응 권고 전문가. JSON 스키마에 맞춰 응답."},
216
+ {"role": "user", "content": user},
217
+ ],
218
+ _T4_SCHEMA,
219
+ "tier4_part",
220
+ )
221
+ trace["llm_calls"] = 1
222
+ trace["tool_calls"] = 0
223
+ trace["unique_tools"] = 0
224
+ trace["input_tokens"] = resp.usage.prompt_tokens
225
+ trace["output_tokens"] = resp.usage.completion_tokens
226
+ llm_out = json.loads(resp.choices[0].message.content)
227
+ refs = [{"id": d, "desc": d} for d in doc_ids]
228
+ return {"immediate": llm_out["immediate"], "longterm": llm_out["longterm"], "refs": refs}
229
+
230
+
231
+ # ==================== Agentic 버전 wrapper (trace에 token 합계 추가) ====================
232
+
233
+ def _run_agentic_with_token_capture(fn, *args, trace: dict):
234
+ """현재 agentic 함수는 LLM resp.usage를 직접 노출 안 함 - monkey patch로 capture"""
235
+ captured = {"input": 0, "output": 0}
236
+ real_create = client().chat.completions.create
237
+
238
+ def patched(**kwargs):
239
+ r = real_create(**kwargs)
240
+ captured["input"] += r.usage.prompt_tokens
241
+ captured["output"] += r.usage.completion_tokens
242
+ return r
243
+
244
+ client().chat.completions.create = patched
245
+ try:
246
+ result = fn(*args, trace=trace)
247
+ finally:
248
+ client().chat.completions.create = real_create
249
+ trace["input_tokens"] = captured["input"]
250
+ trace["output_tokens"] = captured["output"]
251
+ trace["unique_tools"] = len({tc["name"] for tc in trace.get("tool_calls", [])})
252
+ trace["tool_calls_count"] = len(trace.get("tool_calls", []))
253
+ return result
254
+
255
+
256
+ # ==================== Sample 수집 ====================
257
+
258
+ def _alarm_by_id(aid: str) -> dict:
259
+ return next(a for a in DEFAULT_ALARMS if a["id"] == aid)
260
+
261
+
262
+ def collect_samples():
263
+ rows = []
264
+ for aid in ALARMS:
265
+ alarm = _alarm_by_id(aid)
266
+ tier1 = run_detection(alarm)
267
+ print(f"\n=== [{aid}] {alarm['title']} (T1 score={tier1['score']}) ===")
268
+
269
+ # --- Workflow ---
270
+ print(" [Workflow] T2 -> T3 -> T4")
271
+ wf_traces = {"tier2": {}, "tier3": {}, "tier4": {}}
272
+ wf_tier_lat = {}
273
+ t0 = time.time(); wf_t2 = workflow_run_cause(alarm, tier1, wf_traces["tier2"]); wf_tier_lat["tier2"] = (time.time() - t0) * 1000
274
+ t0 = time.time(); wf_t3 = workflow_run_impact(alarm, tier1, wf_t2, wf_traces["tier3"]); wf_tier_lat["tier3"] = (time.time() - t0) * 1000
275
+ t0 = time.time(); wf_t4 = workflow_run_response(alarm, tier1, wf_t2, wf_t3, wf_traces["tier4"]); wf_tier_lat["tier4"] = (time.time() - t0) * 1000
276
+ wf_citations = set()
277
+ for c in wf_t2["causes"]: wf_citations.update(c.get("citations", []))
278
+ for r in wf_t4["refs"]: wf_citations.add(r["id"])
279
+
280
+ # --- Agentic ---
281
+ print(" [Agentic] T2 -> T3 -> T4")
282
+ ag_traces = {"tier2": {}, "tier3": {}, "tier4": {}}
283
+ ag_tier_lat = {}
284
+ t0 = time.time(); ag_t2 = _run_agentic_with_token_capture(agentic_cause, alarm, tier1, trace=ag_traces["tier2"]); ag_tier_lat["tier2"] = (time.time() - t0) * 1000
285
+ t0 = time.time(); ag_t3 = _run_agentic_with_token_capture(agentic_impact, alarm, tier1, ag_t2, trace=ag_traces["tier3"]); ag_tier_lat["tier3"] = (time.time() - t0) * 1000
286
+ t0 = time.time(); ag_t4 = _run_agentic_with_token_capture(agentic_response, alarm, tier1, ag_t2, ag_t3, trace=ag_traces["tier4"]); ag_tier_lat["tier4"] = (time.time() - t0) * 1000
287
+ ag_citations = set()
288
+ for c in ag_t2["causes"]: ag_citations.update(c.get("citations", []))
289
+ for r in ag_t4["refs"]: ag_citations.add(r["id"])
290
+
291
+ rows.append({
292
+ "alarm": aid,
293
+ "workflow": {
294
+ "traces": wf_traces, "tier_latency_ms": wf_tier_lat,
295
+ "unique_citations": len(wf_citations), "citations": sorted(wf_citations),
296
+ },
297
+ "agentic": {
298
+ "traces": ag_traces, "tier_latency_ms": ag_tier_lat,
299
+ "unique_citations": len(ag_citations), "citations": sorted(ag_citations),
300
+ },
301
+ })
302
+
303
+ # 진행 출력
304
+ for pat, key in [("Workflow", "workflow"), ("Agentic", "agentic")]:
305
+ tr = rows[-1][key]["traces"]
306
+ llm = sum(t.get("llm_calls", 0) for t in tr.values())
307
+ tool = sum(t.get("tool_calls_count", t.get("tool_calls", 0)) if isinstance(t.get("tool_calls"), list) else t.get("tool_calls", 0) for t in tr.values())
308
+ print(f" {pat}: LLM={llm}, tools={tool}, citations={rows[-1][key]['unique_citations']}, total_lat={sum(rows[-1][key]['tier_latency_ms'].values()):.0f}ms")
309
+ return rows
310
+
311
+
312
+ # ==================== 집계 + 차트 + 결과 ====================
313
+
314
+ def aggregate(rows):
315
+ def per_pat(key):
316
+ llm = [sum(r[key]["traces"][t].get("llm_calls", 0) for t in ("tier2", "tier3", "tier4")) for r in rows]
317
+ tools = []
318
+ for r in rows:
319
+ total = 0
320
+ for t in ("tier2", "tier3", "tier4"):
321
+ tc = r[key]["traces"][t].get("tool_calls")
322
+ if isinstance(tc, list):
323
+ total += len(tc)
324
+ else:
325
+ total += tc or 0
326
+ tools.append(total)
327
+ lat = [sum(r[key]["tier_latency_ms"].values()) for r in rows]
328
+ cit = [r[key]["unique_citations"] for r in rows]
329
+ inp = [sum(r[key]["traces"][t].get("input_tokens", 0) for t in ("tier2", "tier3", "tier4")) for r in rows]
330
+ out = [sum(r[key]["traces"][t].get("output_tokens", 0) for t in ("tier2", "tier3", "tier4")) for r in rows]
331
+ return {
332
+ "llm_calls": np.mean(llm), "tool_calls": np.mean(tools),
333
+ "latency_ms": np.mean(lat), "unique_citations": np.mean(cit),
334
+ "input_tokens": np.mean(inp), "output_tokens": np.mean(out),
335
+ }
336
+ return {"workflow": per_pat("workflow"), "agentic": per_pat("agentic")}
337
+
338
+
339
+ def make_charts(agg, rows):
340
+ CHART_DIR.mkdir(exist_ok=True)
341
+ wf, ag = agg["workflow"], agg["agentic"]
342
+
343
+ # 1. 호출·도구 비교
344
+ fig, ax = plt.subplots(figsize=(9, 5))
345
+ metrics = ["LLM 호출", "Tool 호출", "유니크 인용"]
346
+ wf_vals = [wf["llm_calls"], wf["tool_calls"], wf["unique_citations"]]
347
+ ag_vals = [ag["llm_calls"], ag["tool_calls"], ag["unique_citations"]]
348
+ x = np.arange(len(metrics))
349
+ w = 0.35
350
+ bars1 = ax.bar(x - w/2, wf_vals, w, label="Workflow", color="#94a3b8")
351
+ bars2 = ax.bar(x + w/2, ag_vals, w, label="Agentic", color="#3b82f6")
352
+ for bars in (bars1, bars2):
353
+ for b in bars:
354
+ ax.text(b.get_x() + b.get_width()/2, b.get_height() + 0.1, f"{b.get_height():.1f}", ha="center", fontsize=9)
355
+ ax.set_xticks(x); ax.set_xticklabels(metrics)
356
+ ax.set_ylabel("평균 (3 알람)")
357
+ ax.set_title("Workflow vs Agentic - 호출 횟수·인용 깊이")
358
+ ax.legend(); ax.grid(axis="y", alpha=0.3)
359
+ fig.tight_layout(); fig.savefig(CHART_DIR / "calls_citations.png", dpi=150); plt.close(fig)
360
+
361
+ # 2. Latency 분해 (per tier)
362
+ fig, ax = plt.subplots(figsize=(10, 5))
363
+ tiers = ["Tier 2 Cause", "Tier 3 Impact", "Tier 4 Response"]
364
+ wf_lat = [np.mean([r["workflow"]["tier_latency_ms"][f"tier{i}"] for r in rows]) for i in (2, 3, 4)]
365
+ ag_lat = [np.mean([r["agentic"]["tier_latency_ms"][f"tier{i}"] for r in rows]) for i in (2, 3, 4)]
366
+ x = np.arange(len(tiers))
367
+ w = 0.35
368
+ ax.bar(x - w/2, wf_lat, w, label="Workflow", color="#94a3b8")
369
+ ax.bar(x + w/2, ag_lat, w, label="Agentic", color="#3b82f6")
370
+ for i, (wv, av) in enumerate(zip(wf_lat, ag_lat)):
371
+ ax.text(i - w/2, wv + 100, f"{wv:.0f}", ha="center", fontsize=9)
372
+ ax.text(i + w/2, av + 100, f"{av:.0f}", ha="center", fontsize=9)
373
+ ax.set_xticks(x); ax.set_xticklabels(tiers)
374
+ ax.set_ylabel("평균 Latency (ms)")
375
+ ax.set_title("Tier별 Latency 비교")
376
+ ax.legend(); ax.grid(axis="y", alpha=0.3)
377
+ fig.tight_layout(); fig.savefig(CHART_DIR / "latency_per_tier.png", dpi=150); plt.close(fig)
378
+
379
+ # 3. 비용 비교
380
+ fig, ax = plt.subplots(figsize=(8.5, 5))
381
+ wf_cost = (wf["input_tokens"] * PRICE_INPUT + wf["output_tokens"] * PRICE_OUTPUT) / 1_000_000
382
+ ag_cost = (ag["input_tokens"] * PRICE_INPUT + ag["output_tokens"] * PRICE_OUTPUT) / 1_000_000
383
+ labels = ["Workflow", "Agentic"]
384
+ costs = [wf_cost, ag_cost]
385
+ bars = ax.bar(labels, costs, color=["#94a3b8", "#3b82f6"])
386
+ for b, v in zip(bars, costs):
387
+ ax.text(b.get_x() + b.get_width()/2, v + max(costs) * 0.02, f"${v*1000:.2f}/1000회", ha="center", fontsize=10)
388
+ ax.set_ylabel("알람당 평균 USD")
389
+ ax.set_title(f"비용 비교 (gpt-5-mini 단가 기준, in=${PRICE_INPUT}/M, out=${PRICE_OUTPUT}/M)")
390
+ ax.grid(axis="y", alpha=0.3)
391
+ fig.tight_layout(); fig.savefig(CHART_DIR / "cost.png", dpi=150); plt.close(fig)
392
+
393
+
394
+ def write_results(rows, agg):
395
+ wf, ag = agg["workflow"], agg["agentic"]
396
+ wf_cost = (wf["input_tokens"] * PRICE_INPUT + wf["output_tokens"] * PRICE_OUTPUT) / 1_000_000
397
+ ag_cost = (ag["input_tokens"] * PRICE_INPUT + ag["output_tokens"] * PRICE_OUTPUT) / 1_000_000
398
+
399
+ lines = [
400
+ "# Workflow vs Agentic - 정량 비교",
401
+ "",
402
+ "동일한 4-Tier pipeline을 두 가지 패턴으로 실행해 정량 비교합니다.",
403
+ "- **Workflow**: Tier 2/3/4 각 단계가 사전 RAG 1회 + LLM 1회 (구버전)",
404
+ "- **Agentic**: Tier 2/3/4 각 단계가 LLM tool calling 루프 (현재 채택)",
405
+ "",
406
+ f"알람: {', '.join(ALARMS)} (총 {len(ALARMS)}건, SECOM + PHM CMP)",
407
+ "",
408
+ "## 결과 요약 (3 알람 평균)",
409
+ "",
410
+ "| 지표 | Workflow | Agentic | 배수 |",
411
+ "|---|---|---|---|",
412
+ f"| LLM 호출 / 알람 | {wf['llm_calls']:.1f} | {ag['llm_calls']:.1f} | x{ag['llm_calls']/wf['llm_calls']:.1f} |",
413
+ f"| Tool 호출 / 알람 | {wf['tool_calls']:.1f} | {ag['tool_calls']:.1f} | - |",
414
+ f"| 유니크 인용 / 알람 | {wf['unique_citations']:.1f} | {ag['unique_citations']:.1f} | x{ag['unique_citations']/max(wf['unique_citations'],1):.1f} |",
415
+ f"| 입력 토큰 / 알람 | {wf['input_tokens']:.0f} | {ag['input_tokens']:.0f} | x{ag['input_tokens']/wf['input_tokens']:.1f} |",
416
+ f"| 출력 토큰 / 알람 | {wf['output_tokens']:.0f} | {ag['output_tokens']:.0f} | x{ag['output_tokens']/wf['output_tokens']:.1f} |",
417
+ f"| Latency / 알람 (Tier 2~4) | {wf['latency_ms']:.0f} ms | {ag['latency_ms']:.0f} ms | x{ag['latency_ms']/wf['latency_ms']:.1f} |",
418
+ f"| 비용 / 알람 (USD) | ${wf_cost:.5f} | ${ag_cost:.5f} | x{ag_cost/wf_cost:.1f} |",
419
+ "",
420
+ "## 시각화",
421
+ "",
422
+ "### 호출 횟수·인용 깊이",
423
+ "![Calls](charts/calls_citations.png)",
424
+ "",
425
+ "### Tier별 Latency",
426
+ "![Latency](charts/latency_per_tier.png)",
427
+ "",
428
+ "### 비용",
429
+ "![Cost](charts/cost.png)",
430
+ "",
431
+ "## 알람별 상세",
432
+ "",
433
+ ]
434
+ for r in rows:
435
+ lines.append(f"### {r['alarm']}")
436
+ lines.append("")
437
+ lines.append("| 패턴 | Tier | LLM | Tools | Latency(ms) |")
438
+ lines.append("|---|---|---|---|---|")
439
+ for pat in ("workflow", "agentic"):
440
+ for tier in ("tier2", "tier3", "tier4"):
441
+ tr = r[pat]["traces"][tier]
442
+ tc = tr.get("tool_calls")
443
+ tc_count = len(tc) if isinstance(tc, list) else (tc or 0)
444
+ lines.append(
445
+ f"| {pat} | {tier} | {tr.get('llm_calls', 0)} | {tc_count} | "
446
+ f"{r[pat]['tier_latency_ms'][tier]:.0f} |"
447
+ )
448
+ lines.append("")
449
+ lines.append(f"- Workflow 인용: {r['workflow']['citations']}")
450
+ lines.append(f"- Agentic 인용: {r['agentic']['citations']}")
451
+ lines.append("")
452
+
453
+ lines += [
454
+ "## 핵심 인사이트",
455
+ "",
456
+ f"1. **인용 깊이 {ag['unique_citations']/max(wf['unique_citations'],1):.1f}배** - agentic은 도구를 자율 호출해 다양한 소스(INC/FMEA/SOP/incident DB)를 결합",
457
+ f"2. **호출 비용 {ag_cost/wf_cost:.1f}배** - LLM 호출이 평균 {wf['llm_calls']:.0f}회 → {ag['llm_calls']:.0f}회, 입력 토큰도 {ag['input_tokens']/wf['input_tokens']:.1f}배",
458
+ f"3. **Latency {ag['latency_ms']/wf['latency_ms']:.1f}배** - tool calling 루프 + synthesis 추가 호출의 자연스러운 비용",
459
+ "4. **agentic만의 정성 신호**: tool 호출 패턴 자체가 reasoning trace - 어떤 정보를 왜 찾았는지 감사·재현 가능",
460
+ "",
461
+ "## 채택 결론",
462
+ "",
463
+ "**현재 채택: Agentic**",
464
+ "- 인용 깊이·근거 다양성이 결정적 - 반도체 fab 도메인에선 multi-source 근거가 안전성·신뢰성 결정",
465
+ f"- 비용 {ag_cost/wf_cost:.1f}배 증가는 알람당 ${(ag_cost-wf_cost)*1000:.2f}/1000회 수준으로 사업적 영향 무시 가능",
466
+ "- Tool 호출 로그가 자체적인 audit trail이 되어 production observability에 유리",
467
+ "",
468
+ "Latency가 critical한 시나리오에선 Workflow로 환경변수 토글 추가 검토 가능 (현재 미구현).",
469
+ "",
470
+ ]
471
+ (OUT_DIR / "results.md").write_text("\n".join(lines), encoding="utf-8")
472
+ print(f"--- 저장: {OUT_DIR / 'results.md'} ---")
473
+
474
+
475
+ def main():
476
+ rows = collect_samples()
477
+ print("\n=== 집계 ===")
478
+ agg = aggregate(rows)
479
+ for pat, vals in agg.items():
480
+ print(f" {pat}: {vals}")
481
+ make_charts(agg, rows)
482
+ write_results(rows, agg)
483
+
484
+
485
+ if __name__ == "__main__":
486
+ main()
experiments/agentic_vs_workflow/charts/calls_citations.png ADDED
experiments/agentic_vs_workflow/charts/cost.png ADDED
experiments/agentic_vs_workflow/charts/latency_per_tier.png ADDED
experiments/agentic_vs_workflow/results.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Workflow vs Agentic - 정량 비교
2
+
3
+ 동일한 4-Tier pipeline을 두 가지 패턴으로 실행해 정량 비교합니다.
4
+ - **Workflow**: Tier 2/3/4 각 단계가 사전 RAG 1회 + LLM 1회 (구버전)
5
+ - **Agentic**: Tier 2/3/4 각 단계가 LLM tool calling 루프 (현재 채택)
6
+
7
+ 알람: A1, A2, A3 (총 3건, SECOM + PHM CMP)
8
+
9
+ ## 결과 요약 (3 알람 평균)
10
+
11
+ | 지표 | Workflow | Agentic | 배수 |
12
+ |---|---|---|---|
13
+ | LLM 호출 / 알람 | 3.0 | 9.0 | x3.0 |
14
+ | Tool 호출 / 알람 | 0.0 | 13.0 | - |
15
+ | 유니크 인용 / 알람 | 4.0 | 5.0 | x1.2 |
16
+ | 입력 토큰 / 알람 | 5890 | 20474 | x3.5 |
17
+ | 출력 토큰 / 알람 | 5174 | 12574 | x2.4 |
18
+ | Latency / 알람 (Tier 2~4) | 83474 ms | 194066 ms | x2.3 |
19
+ | 비용 / 알람 (USD) | $0.01182 | $0.03027 | x2.6 |
20
+
21
+ ## 시각화
22
+
23
+ ### 호출 횟수·인용 깊이
24
+ ![Calls](charts/calls_citations.png)
25
+
26
+ ### Tier별 Latency
27
+ ![Latency](charts/latency_per_tier.png)
28
+
29
+ ### 비용
30
+ ![Cost](charts/cost.png)
31
+
32
+ ## 알람별 상세
33
+
34
+ ### A1
35
+
36
+ | 패턴 | Tier | LLM | Tools | Latency(ms) |
37
+ |---|---|---|---|---|
38
+ | workflow | tier2 | 1 | 0 | 29758 |
39
+ | workflow | tier3 | 1 | 0 | 7819 |
40
+ | workflow | tier4 | 1 | 0 | 35569 |
41
+ | agentic | tier2 | 3 | 3 | 58921 |
42
+ | agentic | tier3 | 3 | 4 | 48383 |
43
+ | agentic | tier4 | 3 | 7 | 74462 |
44
+
45
+ - Workflow 인용: ['FMEA-PH-007', 'INC-2024-0312', 'INC-AUTO-2026-05-18-A1', 'SOP-PH-LENS-002']
46
+ - Agentic 인용: ['ASML-PH-01', 'FMEA-PH-007', 'INC-2024-0289', 'INC-2024-0312', 'INC-AUTO-2026-05-18-A1']
47
+
48
+ ### A2
49
+
50
+ | 패턴 | Tier | LLM | Tools | Latency(ms) |
51
+ |---|---|---|---|---|
52
+ | workflow | tier2 | 1 | 0 | 34208 |
53
+ | workflow | tier3 | 1 | 0 | 21659 |
54
+ | workflow | tier4 | 1 | 0 | 30072 |
55
+ | agentic | tier2 | 3 | 3 | 82107 |
56
+ | agentic | tier3 | 3 | 4 | 47700 |
57
+ | agentic | tier4 | 3 | 7 | 84102 |
58
+
59
+ - Workflow 인용: ['FMEA-CMP-003', 'FMEA-ET-004', 'INC-ET-2024-0301', 'SOP-PH-LENS-002']
60
+ - Agentic 인용: ['FLOW-PH-DOWN-001', 'FMEA-ET-004', 'INC-2024-0312', 'INC-CMP-2025-0142', 'INC-ET-2024-0301', 'SOP-PH-LENS-002']
61
+
62
+ ### A3
63
+
64
+ | 패턴 | Tier | LLM | Tools | Latency(ms) |
65
+ |---|---|---|---|---|
66
+ | workflow | tier2 | 1 | 0 | 20936 |
67
+ | workflow | tier3 | 1 | 0 | 25591 |
68
+ | workflow | tier4 | 1 | 0 | 44811 |
69
+ | agentic | tier2 | 3 | 3 | 69289 |
70
+ | agentic | tier3 | 3 | 4 | 48960 |
71
+ | agentic | tier4 | 3 | 4 | 68274 |
72
+
73
+ - Workflow 인용: ['FMEA-CMP-003', 'INC-CMP-2025-0142', 'INC-ET-2024-0301', 'SOP-CMP-SLURRY-001']
74
+ - Agentic 인용: ['FLOW-CMP-DOWN-001', 'FMEA-CMP-003', 'INC-CMP-2025-0142', 'SOP-CMP-SLURRY-001']
75
+
76
+ ## 핵심 인사이트
77
+
78
+ 1. **인용 깊이 1.2배** - agentic은 도구를 자율 호출해 다양한 소스(INC/FMEA/SOP/incident DB)를 결합
79
+ 2. **호출 비용 2.6배** - LLM 호출이 평균 3회 → 9회, 입력 토큰도 3.5배
80
+ 3. **Latency 2.3배** - tool calling 루프 + synthesis 추가 호출의 자연스러운 비용
81
+ 4. **agentic만의 정성 신호**: tool 호출 패턴 자체가 reasoning trace - 어떤 정보를 왜 찾았는지 감사·재현 가능
82
+
83
+ ## 채택 결론
84
+
85
+ **현재 채택: Agentic**
86
+ - 인용 깊이·근거 다양성이 결정적 - 반도체 fab 도메인에선 multi-source 근거가 안전성·신뢰성 결정
87
+ - 비용 2.6배 증가는 알람당 $18.45/1000회 수준으로 사업적 영향 무시 가능
88
+ - Tool 호출 로그가 자체적인 audit trail이 되어 production observability에 유리
89
+
90
+ Latency가 critical한 시나리오에선 Workflow로 환경변수 토글 추가 검토 가능 (현재 미구현).