hee_!J commited on
Commit ·
3fb690f
1
Parent(s): aab1147
feat(conductor): Plan-and-Execute 패턴 - Central Planner + Tier executor (env AGENT_MODE)
Browse files- agents/cause.py +90 -12
- agents/impact.py +102 -4
- agents/orchestrator.py +127 -80
- agents/planner.py +184 -0
- agents/response.py +107 -4
agents/cause.py
CHANGED
|
@@ -1,13 +1,12 @@
|
|
| 1 |
-
"""Tier 2 원인 분석 에이전트
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
1. system prompt + 알람·Tier1 컨텍스트로 시작 (사전 retrieval 없음)
|
| 8 |
-
2. tool-calling loop: LLM이 필요한 도구를 호출 -> 결과를 컨텍스트에 추가
|
| 9 |
-
3. LLM이 더 호출하지 않을 때(또는 MAX_ITER 도달) synthesis 호출
|
| 10 |
-
4. response_format=json_schema 로 TIER2_SCHEMA 구조화 출력
|
| 11 |
"""
|
| 12 |
import json
|
| 13 |
|
|
@@ -94,15 +93,93 @@ def _assistant_msg_dict(msg) -> dict:
|
|
| 94 |
return out
|
| 95 |
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
@traceable(name="Tier2_Cause_Agent", run_type="chain")
|
| 98 |
def run_cause(
|
| 99 |
-
alarm: dict,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
) -> Tier2:
|
| 101 |
-
"""원인 분석
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
retry_hint=True 면
|
| 104 |
-
더 적극적으로 도구를 호출하도록 유도 (orchestrator의 confidence retry용)
|
| 105 |
"""
|
|
|
|
|
|
|
| 106 |
user_prompt = _initial_user_prompt(alarm, tier1)
|
| 107 |
if retry_hint:
|
| 108 |
user_prompt += (
|
|
@@ -154,5 +231,6 @@ def run_cause(
|
|
| 154 |
trace["tool_calls"] = tool_call_log
|
| 155 |
trace["iterations"] = iterations
|
| 156 |
trace["llm_calls"] = iterations + 1
|
|
|
|
| 157 |
|
| 158 |
return result
|
|
|
|
| 1 |
+
"""Tier 2 원인 분석 에이전트
|
| 2 |
|
| 3 |
+
두 모드 지원:
|
| 4 |
+
1. **Autonomous (기본, plan=None)**: LLM이 tool을 자율 호출하는 agent loop
|
| 5 |
+
- 2~3 iteration + synthesis = LLM 호출 3~4회
|
| 6 |
+
2. **Conductor (plan 제공)**: Planner가 지정한 tool 호출 + 단일 LLM synthesis
|
| 7 |
+
- Tool 직접 실행 + LLM 호출 1회. 재귀·loop 없음
|
| 8 |
|
| 9 |
+
가용 도구: search_knowledge, lookup_incident_history, get_pm_history
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
"""
|
| 11 |
import json
|
| 12 |
|
|
|
|
| 93 |
return out
|
| 94 |
|
| 95 |
|
| 96 |
+
CONDUCTOR_SYSTEM_PROMPT = """당신은 반도체 공정 원인 분석 전문가입니다.
|
| 97 |
+
Central Planner가 이미 필요한 정보를 모두 수집해 [수집된 컨텍스트]에 정리해 두었습니다.
|
| 98 |
+
당신은 추가 도구 호출 없이 그 컨텍스트만 사용해 원인 2~3개를 산출하세요.
|
| 99 |
+
|
| 100 |
+
[최종 산출물]
|
| 101 |
+
- causes: 2~3개. 각 원인은 name / pct(기여도 %) / evidence(구체적 근거) / citations(문서 ID 또는 incident ID)
|
| 102 |
+
- pct 합은 100에 가까워야 함, 기여도 높은 원인부터 정렬
|
| 103 |
+
- 제공되지 않은 정보는 인용하지 마세요"""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _execute_tier2_plan(plan_tier2: dict, trace_calls: list) -> str:
|
| 107 |
+
"""Planner가 지정한 tool들을 직접 호출하고 컨텍스트로 변환"""
|
| 108 |
+
blocks = []
|
| 109 |
+
for query in plan_tier2.get("search_queries", []):
|
| 110 |
+
result = dispatch_tool("search_knowledge", {"query": query})
|
| 111 |
+
trace_calls.append({"name": "search_knowledge", "args": {"query": query}})
|
| 112 |
+
blocks.append(f"[search_knowledge: {query!r}]\n{result}")
|
| 113 |
+
for symptom in plan_tier2.get("incident_symptoms", []):
|
| 114 |
+
result = dispatch_tool("lookup_incident_history", {"symptom": symptom})
|
| 115 |
+
trace_calls.append({"name": "lookup_incident_history", "args": {"symptom": symptom}})
|
| 116 |
+
blocks.append(f"[lookup_incident_history: {symptom!r}]\n{result}")
|
| 117 |
+
for eq_id in plan_tier2.get("equipment_ids", []):
|
| 118 |
+
result = dispatch_tool("get_pm_history", {"equipment_id": eq_id})
|
| 119 |
+
trace_calls.append({"name": "get_pm_history", "args": {"equipment_id": eq_id}})
|
| 120 |
+
blocks.append(f"[get_pm_history: {eq_id!r}]\n{result}")
|
| 121 |
+
return "\n\n".join(blocks) if blocks else "(planner가 정보 수집 지시 없음)"
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _run_cause_conductor(alarm: dict, tier1: Tier1, plan: dict, trace: dict | None) -> Tier2:
|
| 125 |
+
"""Conductor 모드: plan대로 tool 실행 + 1회 LLM synthesis"""
|
| 126 |
+
tool_log: list[dict] = []
|
| 127 |
+
knowledge = _execute_tier2_plan(plan.get("tier2", {}), tool_log)
|
| 128 |
+
|
| 129 |
+
sensors = ", ".join(f["name"] for f in tier1["features"])
|
| 130 |
+
user_prompt = f"""## 이상 알람
|
| 131 |
+
- 공정: {alarm['title']}
|
| 132 |
+
- lot: {alarm['lot_id']}
|
| 133 |
+
- 이상 피처: {alarm.get('feature')} {alarm.get('feature_arrow') or ''}
|
| 134 |
+
|
| 135 |
+
## Tier 1 이상 탐지 결과
|
| 136 |
+
- 이상 점수: {tier1['score']}
|
| 137 |
+
- 기여 센서(Top): {sensors}
|
| 138 |
+
|
| 139 |
+
## 수집된 컨텍스트 (Planner 지정)
|
| 140 |
+
{knowledge}
|
| 141 |
+
|
| 142 |
+
위 컨텍스트만 사용해 원인을 분석하세요."""
|
| 143 |
+
|
| 144 |
+
resp = client().chat.completions.create(
|
| 145 |
+
model=SUBAGENT_MODEL,
|
| 146 |
+
messages=[
|
| 147 |
+
{"role": "system", "content": CONDUCTOR_SYSTEM_PROMPT},
|
| 148 |
+
{"role": "user", "content": user_prompt},
|
| 149 |
+
],
|
| 150 |
+
response_format={
|
| 151 |
+
"type": "json_schema",
|
| 152 |
+
"json_schema": {"name": "tier2", "schema": TIER2_SCHEMA, "strict": True},
|
| 153 |
+
},
|
| 154 |
+
)
|
| 155 |
+
result = json.loads(resp.choices[0].message.content)
|
| 156 |
+
|
| 157 |
+
if trace is not None:
|
| 158 |
+
trace["tool_calls"] = tool_log
|
| 159 |
+
trace["iterations"] = 0
|
| 160 |
+
trace["llm_calls"] = 1
|
| 161 |
+
trace["mode"] = "conductor"
|
| 162 |
+
|
| 163 |
+
return result
|
| 164 |
+
|
| 165 |
+
|
| 166 |
@traceable(name="Tier2_Cause_Agent", run_type="chain")
|
| 167 |
def run_cause(
|
| 168 |
+
alarm: dict,
|
| 169 |
+
tier1: Tier1,
|
| 170 |
+
trace: dict | None = None,
|
| 171 |
+
retry_hint: bool = False,
|
| 172 |
+
plan: dict | None = None,
|
| 173 |
) -> Tier2:
|
| 174 |
+
"""원인 분석 실행
|
| 175 |
+
|
| 176 |
+
plan 제공 시 conductor 모드 (단일 LLM 호출, tool 직접 실행).
|
| 177 |
+
plan=None이면 기존 autonomous tool-calling loop 모드.
|
| 178 |
|
| 179 |
+
retry_hint=True 면 autonomous 모드에서 더 적극적으로 도구를 호출하도록 유도.
|
|
|
|
| 180 |
"""
|
| 181 |
+
if plan is not None:
|
| 182 |
+
return _run_cause_conductor(alarm, tier1, plan, trace)
|
| 183 |
user_prompt = _initial_user_prompt(alarm, tier1)
|
| 184 |
if retry_hint:
|
| 185 |
user_prompt += (
|
|
|
|
| 231 |
trace["tool_calls"] = tool_call_log
|
| 232 |
trace["iterations"] = iterations
|
| 233 |
trace["llm_calls"] = iterations + 1
|
| 234 |
+
trace["mode"] = "autonomous"
|
| 235 |
|
| 236 |
return result
|
agents/impact.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
"""Tier 3 공정 간 영향 평가 에이전트
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
| 5 |
|
| 6 |
가용 도구: query_wip_status, get_downstream_steps, get_yield_baseline, get_pm_history
|
| 7 |
"""
|
|
@@ -87,8 +88,104 @@ def _initial_user_prompt(alarm: dict, tier1: Tier1, tier2: Tier2) -> str:
|
|
| 87 |
WIP·downstream·yield·PM 컨텍스트는 도구를 호출해 자율적으로 수집하세요."""
|
| 88 |
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
@traceable(name="Tier3_Impact_Agent", run_type="chain")
|
| 91 |
-
def run_impact(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
messages = [
|
| 93 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 94 |
{"role": "user", "content": _initial_user_prompt(alarm, tier1, tier2)},
|
|
@@ -141,6 +238,7 @@ def run_impact(alarm: dict, tier1: Tier1, tier2: Tier2, trace: dict | None = Non
|
|
| 141 |
trace["tool_calls"] = tool_call_log
|
| 142 |
trace["iterations"] = iterations
|
| 143 |
trace["llm_calls"] = iterations + 1
|
|
|
|
| 144 |
|
| 145 |
return {
|
| 146 |
"yield_loss": round(float(llm_out["yield_loss"]), 1),
|
|
|
|
| 1 |
+
"""Tier 3 공정 간 영향 평가 에이전트
|
| 2 |
|
| 3 |
+
두 모드 지원:
|
| 4 |
+
1. Autonomous (plan=None): LLM이 tool을 자율 호출하는 agent loop
|
| 5 |
+
2. Conductor (plan 제공): Planner가 지정한 tool 호출 + 단일 LLM synthesis
|
| 6 |
|
| 7 |
가용 도구: query_wip_status, get_downstream_steps, get_yield_baseline, get_pm_history
|
| 8 |
"""
|
|
|
|
| 88 |
WIP·downstream·yield·PM 컨텍스트는 도구를 호출해 자율적으로 수집하세요."""
|
| 89 |
|
| 90 |
|
| 91 |
+
CONDUCTOR_SYSTEM_PROMPT = """당신은 반도체 공정 영향 평가 전문가입니다.
|
| 92 |
+
Central Planner가 이미 필요한 정보(WIP·downstream·yield·PM)를 모두 수집해 [수집된 컨텍스트]에 정리해 두었습니다.
|
| 93 |
+
당신은 추가 도구 호출 없이 그 컨텍스트만 사용해 산출하세요.
|
| 94 |
+
|
| 95 |
+
[최종 산출물]
|
| 96 |
+
- yield_loss: 본 이상으로 인한 예상 수율 손실(%p, 소수 한 자리)
|
| 97 |
+
- downstream_dependencies: 영향 받는 후공정 (current 제외) - stage / delta / tag / kind"""
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _execute_tier3_plan(plan_tier3: dict, trace_calls: list) -> str:
|
| 101 |
+
"""Planner가 지정한 tool들을 직접 호출하고 컨텍스트로 변환"""
|
| 102 |
+
blocks = []
|
| 103 |
+
if plan_tier3.get("alarm_id"):
|
| 104 |
+
r = dispatch_tool("query_wip_status", {"alarm_id": plan_tier3["alarm_id"]})
|
| 105 |
+
trace_calls.append({"name": "query_wip_status", "args": {"alarm_id": plan_tier3["alarm_id"]}})
|
| 106 |
+
blocks.append(f"[query_wip_status: {plan_tier3['alarm_id']!r}]\n{r}")
|
| 107 |
+
for stage in plan_tier3.get("downstream_stages", []):
|
| 108 |
+
r = dispatch_tool("get_downstream_steps", {"current_stage": stage})
|
| 109 |
+
trace_calls.append({"name": "get_downstream_steps", "args": {"current_stage": stage}})
|
| 110 |
+
blocks.append(f"[get_downstream_steps: {stage!r}]\n{r}")
|
| 111 |
+
for proc in plan_tier3.get("yield_processes", []):
|
| 112 |
+
r = dispatch_tool("get_yield_baseline", {"process": proc})
|
| 113 |
+
trace_calls.append({"name": "get_yield_baseline", "args": {"process": proc}})
|
| 114 |
+
blocks.append(f"[get_yield_baseline: {proc!r}]\n{r}")
|
| 115 |
+
for eq_id in plan_tier3.get("equipment_ids", []):
|
| 116 |
+
r = dispatch_tool("get_pm_history", {"equipment_id": eq_id})
|
| 117 |
+
trace_calls.append({"name": "get_pm_history", "args": {"equipment_id": eq_id}})
|
| 118 |
+
blocks.append(f"[get_pm_history: {eq_id!r}]\n{r}")
|
| 119 |
+
return "\n\n".join(blocks) if blocks else "(planner가 정보 수집 지시 없음)"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _run_impact_conductor(
|
| 123 |
+
alarm: dict, tier1: Tier1, tier2: Tier2, plan: dict, trace: dict | None
|
| 124 |
+
) -> Tier3:
|
| 125 |
+
tool_log: list[dict] = []
|
| 126 |
+
knowledge = _execute_tier3_plan(plan.get("tier3", {}), tool_log)
|
| 127 |
+
|
| 128 |
+
cause_lines = "\n".join(
|
| 129 |
+
f"- {c['name']} ({c['pct']}%): {c['evidence'][:120]}" for c in tier2["causes"]
|
| 130 |
+
)
|
| 131 |
+
current_stage = _stage_from_alarm(alarm)
|
| 132 |
+
user_prompt = f"""## 이상 알람
|
| 133 |
+
- 공정: {alarm['title']} (current_stage: {current_stage})
|
| 134 |
+
|
| 135 |
+
## Tier 1: 이상 점수 {tier1['score']}
|
| 136 |
+
|
| 137 |
+
## Tier 2 원인 분석
|
| 138 |
+
{cause_lines}
|
| 139 |
+
|
| 140 |
+
## 수집된 컨텍스트 (Planner 지정)
|
| 141 |
+
{knowledge}
|
| 142 |
+
|
| 143 |
+
위 컨텍스트만 사용해 yield_loss와 downstream_dependencies를 산출하세요."""
|
| 144 |
+
|
| 145 |
+
resp = client().chat.completions.create(
|
| 146 |
+
model=SUBAGENT_MODEL,
|
| 147 |
+
messages=[
|
| 148 |
+
{"role": "system", "content": CONDUCTOR_SYSTEM_PROMPT},
|
| 149 |
+
{"role": "user", "content": user_prompt},
|
| 150 |
+
],
|
| 151 |
+
response_format={
|
| 152 |
+
"type": "json_schema",
|
| 153 |
+
"json_schema": {"name": "tier3_part", "schema": LLM_PART_SCHEMA, "strict": True},
|
| 154 |
+
},
|
| 155 |
+
)
|
| 156 |
+
llm_out = json.loads(resp.choices[0].message.content)
|
| 157 |
+
|
| 158 |
+
current_dep = {
|
| 159 |
+
"stage": current_stage,
|
| 160 |
+
"delta": f"+{tier1['score']}",
|
| 161 |
+
"tag": "현재",
|
| 162 |
+
"kind": "current",
|
| 163 |
+
}
|
| 164 |
+
if trace is not None:
|
| 165 |
+
trace["tool_calls"] = tool_log
|
| 166 |
+
trace["iterations"] = 0
|
| 167 |
+
trace["llm_calls"] = 1
|
| 168 |
+
trace["mode"] = "conductor"
|
| 169 |
+
|
| 170 |
+
return {
|
| 171 |
+
"yield_loss": round(float(llm_out["yield_loss"]), 1),
|
| 172 |
+
"dependencies": [current_dep] + llm_out["downstream_dependencies"],
|
| 173 |
+
"impact_lots": get_affected_wip(alarm["id"]),
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
@traceable(name="Tier3_Impact_Agent", run_type="chain")
|
| 178 |
+
def run_impact(
|
| 179 |
+
alarm: dict,
|
| 180 |
+
tier1: Tier1,
|
| 181 |
+
tier2: Tier2,
|
| 182 |
+
trace: dict | None = None,
|
| 183 |
+
plan: dict | None = None,
|
| 184 |
+
) -> Tier3:
|
| 185 |
+
"""Tier 3 영향 평가. plan 제공 시 conductor 모드(LLM 1회), 아니면 autonomous loop."""
|
| 186 |
+
if plan is not None:
|
| 187 |
+
return _run_impact_conductor(alarm, tier1, tier2, plan, trace)
|
| 188 |
+
|
| 189 |
messages = [
|
| 190 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 191 |
{"role": "user", "content": _initial_user_prompt(alarm, tier1, tier2)},
|
|
|
|
| 238 |
trace["tool_calls"] = tool_call_log
|
| 239 |
trace["iterations"] = iterations
|
| 240 |
trace["llm_calls"] = iterations + 1
|
| 241 |
+
trace["mode"] = "autonomous"
|
| 242 |
|
| 243 |
return {
|
| 244 |
"yield_loss": round(float(llm_out["yield_loss"]), 1),
|
agents/orchestrator.py
CHANGED
|
@@ -1,24 +1,26 @@
|
|
| 1 |
"""4-Tier 멀티에이전트 오케스트레이터 (LangGraph 기반)
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 21 |
"""
|
|
|
|
| 22 |
from functools import lru_cache
|
| 23 |
from typing import TypedDict
|
| 24 |
|
|
@@ -28,6 +30,7 @@ from langsmith import traceable
|
|
| 28 |
from agents.cause import run_cause
|
| 29 |
from agents.detection import run_detection
|
| 30 |
from agents.impact import run_impact
|
|
|
|
| 31 |
from agents.response import run_response
|
| 32 |
from agents.supervisor import run_supervisor
|
| 33 |
from core.schema import Tier1, Tier2, Tier3, Tier4, TierData
|
|
@@ -38,6 +41,10 @@ SEVERITY_THRESHOLD = 0.30
|
|
| 38 |
CAUSE_CONFIDENCE_THRESHOLD = 40
|
| 39 |
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
class _GraphState(TypedDict, total=False):
|
| 42 |
alarm: dict
|
| 43 |
tier1: Tier1
|
|
@@ -46,7 +53,8 @@ class _GraphState(TypedDict, total=False):
|
|
| 46 |
tier4: Tier4
|
| 47 |
skipped: bool
|
| 48 |
cause_retried: bool
|
| 49 |
-
supervisor_decision: dict
|
|
|
|
| 50 |
|
| 51 |
|
| 52 |
def _node_detect(state: _GraphState) -> dict:
|
|
@@ -54,7 +62,7 @@ def _node_detect(state: _GraphState) -> dict:
|
|
| 54 |
|
| 55 |
|
| 56 |
def _route_after_detect(state: _GraphState) -> str:
|
| 57 |
-
return "
|
| 58 |
|
| 59 |
|
| 60 |
def _node_noise(state: _GraphState) -> dict:
|
|
@@ -66,52 +74,34 @@ def _node_noise(state: _GraphState) -> dict:
|
|
| 66 |
}
|
| 67 |
|
| 68 |
|
| 69 |
-
|
| 70 |
-
return {"tier2": run_cause(state["alarm"], state["tier1"])}
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def _route_after_cause(state: _GraphState) -> str:
|
| 74 |
-
if state.get("cause_retried"):
|
| 75 |
-
return "supervisor" # 이미 재시도 - supervisor로 직행
|
| 76 |
-
causes = state["tier2"]["causes"]
|
| 77 |
-
max_pct = max((c.get("pct", 0) for c in causes), default=0)
|
| 78 |
-
return "cause_retry" if max_pct < CAUSE_CONFIDENCE_THRESHOLD else "supervisor"
|
| 79 |
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
def _node_cause_retry(state: _GraphState) -> dict:
|
| 82 |
-
return {
|
| 83 |
-
"tier2": run_cause(state["alarm"], state["tier1"], retry_hint=True),
|
| 84 |
-
"cause_retried": True,
|
| 85 |
-
}
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
def _node_supervisor(state: _GraphState) -> dict:
|
| 89 |
-
decision = run_supervisor(state["alarm"], state["tier1"], state["tier2"])
|
| 90 |
-
return {"supervisor_decision": decision}
|
| 91 |
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
def _route_after_supervisor(state: _GraphState) -> str:
|
| 94 |
-
action = state["supervisor_decision"]["action"]
|
| 95 |
-
if action == "fast_track":
|
| 96 |
-
return "fast_impact"
|
| 97 |
-
return "impact" # proceed_full + escalate 모두 impact 경유
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
return {"tier3": run_impact(state["alarm"], state["tier1"], state["tier2"])}
|
| 102 |
|
| 103 |
|
| 104 |
def _node_fast_impact(state: _GraphState) -> dict:
|
| 105 |
-
"""fast_track: LLM 호출 없
|
| 106 |
-
|
| 107 |
-
Tier 4가 tier3을 요구하므로 최소 정보만 채워 전달.
|
| 108 |
-
yield_loss는 tier1 score를 단순 변환, downstream은 current stage만.
|
| 109 |
-
"""
|
| 110 |
alarm = state["alarm"]
|
| 111 |
tier1 = state["tier1"]
|
| 112 |
return {
|
| 113 |
"tier3": {
|
| 114 |
-
"yield_loss": round(float(tier1["score"]) * 3.0, 1),
|
| 115 |
"dependencies": [{
|
| 116 |
"stage": alarm["title"].split()[0],
|
| 117 |
"delta": f"+{tier1['score']}",
|
|
@@ -123,45 +113,102 @@ def _node_fast_impact(state: _GraphState) -> dict:
|
|
| 123 |
}
|
| 124 |
|
| 125 |
|
| 126 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
tier4 = run_response(state["alarm"], state["tier1"], state["tier2"], state["tier3"])
|
| 128 |
-
# supervisor가 escalate 결정 시 immediate 첫 항목에 human review 플래그 추가
|
| 129 |
decision = state.get("supervisor_decision", {})
|
| 130 |
if decision.get("action") == "escalate" and tier4.get("immediate"):
|
| 131 |
tier4["immediate"][0]["text"] = "🚨 [HUMAN REVIEW 요구] " + tier4["immediate"][0]["text"]
|
| 132 |
return {"tier4": tier4}
|
| 133 |
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
| 137 |
g = StateGraph(_GraphState)
|
| 138 |
g.add_node("detect", _node_detect)
|
| 139 |
g.add_node("noise", _node_noise)
|
| 140 |
-
g.add_node("cause", _node_cause)
|
| 141 |
-
g.add_node("cause_retry", _node_cause_retry)
|
| 142 |
-
g.add_node("supervisor", _node_supervisor)
|
| 143 |
-
g.add_node("impact", _node_impact)
|
| 144 |
-
g.add_node("fast_impact", _node_fast_impact)
|
| 145 |
-
g.add_node("response", _node_response)
|
| 146 |
-
|
| 147 |
g.add_edge(START, "detect")
|
| 148 |
-
g.add_conditional_edges("detect", _route_after_detect, {
|
| 149 |
-
"cause": "cause",
|
| 150 |
-
"noise": "noise",
|
| 151 |
-
})
|
| 152 |
g.add_edge("noise", END)
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
"
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
"
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
return g.compile()
|
| 166 |
|
| 167 |
|
|
@@ -176,7 +223,7 @@ def _find_alarm(alarm_id: str) -> dict:
|
|
| 176 |
@lru_cache(maxsize=8)
|
| 177 |
def run_orchestrator(alarm_id: str) -> TierData:
|
| 178 |
alarm = _find_alarm(alarm_id)
|
| 179 |
-
graph = build_graph()
|
| 180 |
final = graph.invoke({"alarm": alarm})
|
| 181 |
return {
|
| 182 |
"tier1": final["tier1"],
|
|
|
|
| 1 |
"""4-Tier 멀티에이전트 오케스트레이터 (LangGraph 기반)
|
| 2 |
|
| 3 |
+
두 가지 실행 모드 지원 (환경변수 AGENT_MODE):
|
| 4 |
+
- **conductor** (기본): Central Planner Agent가 전체 plan 1회 산출
|
| 5 |
+
각 Tier executor가 plan대로 tool 호출 + LLM 1회 synthesis
|
| 6 |
+
→ LLM 호출 ~70% 감소, latency 큰 폭 단축
|
| 7 |
+
- **autonomous**: 각 Tier가 tool-using agent loop로 자율 실행
|
| 8 |
+
→ 적응성 높으나 LLM 호출 많음
|
| 9 |
+
|
| 10 |
+
[그래프 - conductor 모드]
|
| 11 |
+
START → detect → (severity gate) → planner → (action 분기)
|
| 12 |
+
↓
|
| 13 |
+
+→ cause → impact → response → END (proceed_full)
|
| 14 |
+
+→ cause → fast_impact → response → END (fast_track)
|
| 15 |
+
+→ cause → impact → response_escalate → END (escalate, T4에 🚨 prepend)
|
| 16 |
+
|
| 17 |
+
[그래프 - autonomous 모드]
|
| 18 |
+
기존 구조 (severity gate + cause_retry + supervisor 분기)
|
| 19 |
+
|
| 20 |
+
알람 dict은 data.demo.DEFAULT_ALARMS에서 ID로 조회.
|
| 21 |
+
@traceable (LangSmith) + wrap_openai 로 LLM·tool 호출 자동 트레이스.
|
| 22 |
"""
|
| 23 |
+
import os
|
| 24 |
from functools import lru_cache
|
| 25 |
from typing import TypedDict
|
| 26 |
|
|
|
|
| 30 |
from agents.cause import run_cause
|
| 31 |
from agents.detection import run_detection
|
| 32 |
from agents.impact import run_impact
|
| 33 |
+
from agents.planner import plan_workflow
|
| 34 |
from agents.response import run_response
|
| 35 |
from agents.supervisor import run_supervisor
|
| 36 |
from core.schema import Tier1, Tier2, Tier3, Tier4, TierData
|
|
|
|
| 41 |
CAUSE_CONFIDENCE_THRESHOLD = 40
|
| 42 |
|
| 43 |
|
| 44 |
+
def _agent_mode() -> str:
|
| 45 |
+
return os.getenv("AGENT_MODE", "conductor").lower()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
class _GraphState(TypedDict, total=False):
|
| 49 |
alarm: dict
|
| 50 |
tier1: Tier1
|
|
|
|
| 53 |
tier4: Tier4
|
| 54 |
skipped: bool
|
| 55 |
cause_retried: bool
|
| 56 |
+
supervisor_decision: dict
|
| 57 |
+
plan: dict # conductor 모드의 Planner 결과
|
| 58 |
|
| 59 |
|
| 60 |
def _node_detect(state: _GraphState) -> dict:
|
|
|
|
| 62 |
|
| 63 |
|
| 64 |
def _route_after_detect(state: _GraphState) -> str:
|
| 65 |
+
return "go" if state["tier1"]["score"] >= SEVERITY_THRESHOLD else "noise"
|
| 66 |
|
| 67 |
|
| 68 |
def _node_noise(state: _GraphState) -> dict:
|
|
|
|
| 74 |
}
|
| 75 |
|
| 76 |
|
| 77 |
+
# ==================== Conductor 모드 노드 ====================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
def _node_planner(state: _GraphState) -> dict:
|
| 80 |
+
return {"plan": plan_workflow(state["alarm"], state["tier1"])}
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
def _route_after_planner(state: _GraphState) -> str:
|
| 84 |
+
action = state["plan"].get("action", "proceed_full")
|
| 85 |
+
if action == "fast_track":
|
| 86 |
+
return "fast_track"
|
| 87 |
+
return "proceed" # proceed_full + escalate 모두 표준 경로
|
| 88 |
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
def _node_cause_conductor(state: _GraphState) -> dict:
|
| 91 |
+
return {"tier2": run_cause(state["alarm"], state["tier1"], plan=state["plan"])}
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
+
def _node_impact_conductor(state: _GraphState) -> dict:
|
| 95 |
+
return {"tier3": run_impact(state["alarm"], state["tier1"], state["tier2"], plan=state["plan"])}
|
|
|
|
| 96 |
|
| 97 |
|
| 98 |
def _node_fast_impact(state: _GraphState) -> dict:
|
| 99 |
+
"""fast_track: deterministic 경량 처리 (LLM 호출 없음)"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
alarm = state["alarm"]
|
| 101 |
tier1 = state["tier1"]
|
| 102 |
return {
|
| 103 |
"tier3": {
|
| 104 |
+
"yield_loss": round(float(tier1["score"]) * 3.0, 1),
|
| 105 |
"dependencies": [{
|
| 106 |
"stage": alarm["title"].split()[0],
|
| 107 |
"delta": f"+{tier1['score']}",
|
|
|
|
| 113 |
}
|
| 114 |
|
| 115 |
|
| 116 |
+
def _node_response_conductor(state: _GraphState) -> dict:
|
| 117 |
+
tier4 = run_response(state["alarm"], state["tier1"], state["tier2"], state["tier3"], plan=state["plan"])
|
| 118 |
+
if state["plan"].get("action") == "escalate" and tier4.get("immediate"):
|
| 119 |
+
tier4["immediate"][0]["text"] = "🚨 [HUMAN REVIEW 요구] " + tier4["immediate"][0]["text"]
|
| 120 |
+
return {"tier4": tier4}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# ==================== Autonomous 모드 노드 (기존 보존) ====================
|
| 124 |
+
|
| 125 |
+
def _node_cause_autonomous(state: _GraphState) -> dict:
|
| 126 |
+
return {"tier2": run_cause(state["alarm"], state["tier1"])}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _route_after_cause_autonomous(state: _GraphState) -> str:
|
| 130 |
+
if state.get("cause_retried"):
|
| 131 |
+
return "supervisor"
|
| 132 |
+
causes = state["tier2"]["causes"]
|
| 133 |
+
max_pct = max((c.get("pct", 0) for c in causes), default=0)
|
| 134 |
+
return "cause_retry" if max_pct < CAUSE_CONFIDENCE_THRESHOLD else "supervisor"
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _node_cause_retry(state: _GraphState) -> dict:
|
| 138 |
+
return {
|
| 139 |
+
"tier2": run_cause(state["alarm"], state["tier1"], retry_hint=True),
|
| 140 |
+
"cause_retried": True,
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _node_supervisor(state: _GraphState) -> dict:
|
| 145 |
+
return {"supervisor_decision": run_supervisor(state["alarm"], state["tier1"], state["tier2"])}
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _route_after_supervisor(state: _GraphState) -> str:
|
| 149 |
+
return "fast_track" if state["supervisor_decision"]["action"] == "fast_track" else "proceed"
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _node_impact_autonomous(state: _GraphState) -> dict:
|
| 153 |
+
return {"tier3": run_impact(state["alarm"], state["tier1"], state["tier2"])}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _node_response_autonomous(state: _GraphState) -> dict:
|
| 157 |
tier4 = run_response(state["alarm"], state["tier1"], state["tier2"], state["tier3"])
|
|
|
|
| 158 |
decision = state.get("supervisor_decision", {})
|
| 159 |
if decision.get("action") == "escalate" and tier4.get("immediate"):
|
| 160 |
tier4["immediate"][0]["text"] = "🚨 [HUMAN REVIEW 요구] " + tier4["immediate"][0]["text"]
|
| 161 |
return {"tier4": tier4}
|
| 162 |
|
| 163 |
|
| 164 |
+
# ==================== Graph 빌더 ====================
|
| 165 |
+
|
| 166 |
+
@lru_cache(maxsize=2)
|
| 167 |
+
def build_graph(mode: str = "conductor"):
|
| 168 |
g = StateGraph(_GraphState)
|
| 169 |
g.add_node("detect", _node_detect)
|
| 170 |
g.add_node("noise", _node_noise)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
g.add_edge(START, "detect")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
g.add_edge("noise", END)
|
| 173 |
+
|
| 174 |
+
if mode == "conductor":
|
| 175 |
+
g.add_node("planner", _node_planner)
|
| 176 |
+
g.add_node("cause", _node_cause_conductor)
|
| 177 |
+
g.add_node("impact", _node_impact_conductor)
|
| 178 |
+
g.add_node("fast_impact", _node_fast_impact)
|
| 179 |
+
g.add_node("response", _node_response_conductor)
|
| 180 |
+
|
| 181 |
+
g.add_conditional_edges("detect", _route_after_detect, {"go": "planner", "noise": "noise"})
|
| 182 |
+
g.add_edge("planner", "cause")
|
| 183 |
+
g.add_conditional_edges("cause", _route_after_planner, {
|
| 184 |
+
"proceed": "impact",
|
| 185 |
+
"fast_track": "fast_impact",
|
| 186 |
+
})
|
| 187 |
+
g.add_edge("impact", "response")
|
| 188 |
+
g.add_edge("fast_impact", "response")
|
| 189 |
+
g.add_edge("response", END)
|
| 190 |
+
else:
|
| 191 |
+
# autonomous (기존 구조)
|
| 192 |
+
g.add_node("cause", _node_cause_autonomous)
|
| 193 |
+
g.add_node("cause_retry", _node_cause_retry)
|
| 194 |
+
g.add_node("supervisor", _node_supervisor)
|
| 195 |
+
g.add_node("impact", _node_impact_autonomous)
|
| 196 |
+
g.add_node("fast_impact", _node_fast_impact)
|
| 197 |
+
g.add_node("response", _node_response_autonomous)
|
| 198 |
+
|
| 199 |
+
g.add_conditional_edges("detect", _route_after_detect, {"go": "cause", "noise": "noise"})
|
| 200 |
+
g.add_conditional_edges("cause", _route_after_cause_autonomous, {
|
| 201 |
+
"supervisor": "supervisor",
|
| 202 |
+
"cause_retry": "cause_retry",
|
| 203 |
+
})
|
| 204 |
+
g.add_edge("cause_retry", "supervisor")
|
| 205 |
+
g.add_conditional_edges("supervisor", _route_after_supervisor, {
|
| 206 |
+
"proceed": "impact",
|
| 207 |
+
"fast_track": "fast_impact",
|
| 208 |
+
})
|
| 209 |
+
g.add_edge("impact", "response")
|
| 210 |
+
g.add_edge("fast_impact", "response")
|
| 211 |
+
g.add_edge("response", END)
|
| 212 |
return g.compile()
|
| 213 |
|
| 214 |
|
|
|
|
| 223 |
@lru_cache(maxsize=8)
|
| 224 |
def run_orchestrator(alarm_id: str) -> TierData:
|
| 225 |
alarm = _find_alarm(alarm_id)
|
| 226 |
+
graph = build_graph(_agent_mode())
|
| 227 |
final = graph.invoke({"alarm": alarm})
|
| 228 |
return {
|
| 229 |
"tier1": final["tier1"],
|
agents/planner.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Central Planner Agent (Plan-and-Execute pattern)
|
| 2 |
+
|
| 3 |
+
알람과 Tier 1 결과를 보고 전체 워크플로우 plan을 1회 LLM 호출로 산출합니다.
|
| 4 |
+
각 Tier executor는 plan대로 도구를 직접 호출하고 LLM 1회로 결과를 합성합니다.
|
| 5 |
+
|
| 6 |
+
기존 autonomous tool-using loop 대비:
|
| 7 |
+
- LLM 호출 ~70% 감소 (각 tier loop 제거)
|
| 8 |
+
- 재귀/무한루프 위험 원천 차단 (LLM이 tool을 자율 선택하지 않음)
|
| 9 |
+
- 통신 오버헤드 최소화 (synthesis context를 한 번에 구성)
|
| 10 |
+
- 비용·latency 큰 폭 절감 (gpt-4o-mini로 planning + gpt-5-mini로 synthesis)
|
| 11 |
+
|
| 12 |
+
설계:
|
| 13 |
+
- Planner가 구체적 함수 호출이 아닌 "필요한 정보 채널" (query/symptom/equipment_id 리스트)을 지정
|
| 14 |
+
- 각 Tier executor가 그 채널을 받아 결정론적으로 tool 호출 (병렬 가능)
|
| 15 |
+
- Tier executor는 단 1회 LLM 호출로 synthesis (tools 인자 없이)
|
| 16 |
+
"""
|
| 17 |
+
import json
|
| 18 |
+
|
| 19 |
+
from langsmith import traceable
|
| 20 |
+
|
| 21 |
+
from agents.llm import client
|
| 22 |
+
from agents.tools.equipment import ALARM_EQUIPMENT
|
| 23 |
+
from core.schema import Tier1
|
| 24 |
+
|
| 25 |
+
PLANNER_MODEL = "gpt-4o-mini"
|
| 26 |
+
|
| 27 |
+
PLAN_SCHEMA = {
|
| 28 |
+
"type": "object",
|
| 29 |
+
"properties": {
|
| 30 |
+
"tier2": {
|
| 31 |
+
"type": "object",
|
| 32 |
+
"properties": {
|
| 33 |
+
"search_queries": {
|
| 34 |
+
"type": "array",
|
| 35 |
+
"items": {"type": "string"},
|
| 36 |
+
"description": "사내 지식 검색 쿼리 (1~3개)",
|
| 37 |
+
},
|
| 38 |
+
"incident_symptoms": {
|
| 39 |
+
"type": "array",
|
| 40 |
+
"items": {"type": "string"},
|
| 41 |
+
"description": "과거 incident DB 조회용 증상 (0~2개)",
|
| 42 |
+
},
|
| 43 |
+
"equipment_ids": {
|
| 44 |
+
"type": "array",
|
| 45 |
+
"items": {"type": "string"},
|
| 46 |
+
"description": "PM 이력 조회 장비 ID (0~1개)",
|
| 47 |
+
},
|
| 48 |
+
},
|
| 49 |
+
"required": ["search_queries", "incident_symptoms", "equipment_ids"],
|
| 50 |
+
"additionalProperties": False,
|
| 51 |
+
},
|
| 52 |
+
"tier3": {
|
| 53 |
+
"type": "object",
|
| 54 |
+
"properties": {
|
| 55 |
+
"alarm_id": {"type": "string", "description": "WIP 조회용 알람 ID"},
|
| 56 |
+
"downstream_stages": {
|
| 57 |
+
"type": "array",
|
| 58 |
+
"items": {"type": "string"},
|
| 59 |
+
"description": "후공정 의존성 조회 (1개)",
|
| 60 |
+
},
|
| 61 |
+
"yield_processes": {
|
| 62 |
+
"type": "array",
|
| 63 |
+
"items": {"type": "string"},
|
| 64 |
+
"description": "yield baseline 조회 (1~2개)",
|
| 65 |
+
},
|
| 66 |
+
"equipment_ids": {
|
| 67 |
+
"type": "array",
|
| 68 |
+
"items": {"type": "string"},
|
| 69 |
+
"description": "PM 이력 조회 장비 ID (0~1개)",
|
| 70 |
+
},
|
| 71 |
+
},
|
| 72 |
+
"required": ["alarm_id", "downstream_stages", "yield_processes", "equipment_ids"],
|
| 73 |
+
"additionalProperties": False,
|
| 74 |
+
},
|
| 75 |
+
"tier4": {
|
| 76 |
+
"type": "object",
|
| 77 |
+
"properties": {
|
| 78 |
+
"search_queries": {
|
| 79 |
+
"type": "array",
|
| 80 |
+
"items": {"type": "string"},
|
| 81 |
+
"description": "SOP 검색 쿼리 (1~3개)",
|
| 82 |
+
},
|
| 83 |
+
"incident_symptoms": {
|
| 84 |
+
"type": "array",
|
| 85 |
+
"items": {"type": "string"},
|
| 86 |
+
"description": "과거 해결책 조회 (0~2개)",
|
| 87 |
+
},
|
| 88 |
+
"equipment_ids": {
|
| 89 |
+
"type": "array",
|
| 90 |
+
"items": {"type": "string"},
|
| 91 |
+
"description": "PM 윈도우 조회 장비 ID (1개)",
|
| 92 |
+
},
|
| 93 |
+
},
|
| 94 |
+
"required": ["search_queries", "incident_symptoms", "equipment_ids"],
|
| 95 |
+
"additionalProperties": False,
|
| 96 |
+
},
|
| 97 |
+
"action": {
|
| 98 |
+
"type": "string",
|
| 99 |
+
"enum": ["proceed_full", "fast_track", "escalate"],
|
| 100 |
+
"description": "워크플로우 분기 (Tier 3 skip 여부, escalation 플래그)",
|
| 101 |
+
},
|
| 102 |
+
"severity": {
|
| 103 |
+
"type": "string",
|
| 104 |
+
"enum": ["low", "medium", "high", "critical"],
|
| 105 |
+
},
|
| 106 |
+
"reasoning": {"type": "string"},
|
| 107 |
+
},
|
| 108 |
+
"required": ["tier2", "tier3", "tier4", "action", "severity", "reasoning"],
|
| 109 |
+
"additionalProperties": False,
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
SYSTEM_PROMPT = """당신은 반도체 fab 인시던트 대응 시스템의 Central Planner Agent입니다.
|
| 113 |
+
이상 알람과 Tier 1 탐지 결과를 받아 전체 워크플로우(Tier 2 원인분석 → Tier 3 영향평가 → Tier 4 대응권고)에 필요한 정보 수집 plan을 한 번에 산출합니다.
|
| 114 |
+
|
| 115 |
+
[가용 정보 채널 - tier별]
|
| 116 |
+
|
| 117 |
+
Tier 2 (원인 분석):
|
| 118 |
+
- search_queries: 사내 지식(INC/FMEA/SOP/FLOW) hybrid 검색 (1~3개)
|
| 119 |
+
- incident_symptoms: 과거 incident DB 구조화 조회 (0~2개)
|
| 120 |
+
- equipment_ids: 장비 PM 이력 조회 (0~1개)
|
| 121 |
+
|
| 122 |
+
Tier 3 (영향 평가):
|
| 123 |
+
- alarm_id: WIP 조회 (��드시 1개, 알람 ID 그대로)
|
| 124 |
+
- downstream_stages: 후공정 의존성 (1개, 현재 공정명 - 예: "Photo", "Etch", "CMP")
|
| 125 |
+
- yield_processes: yield baseline 조회 (1~2개)
|
| 126 |
+
- equipment_ids: PM 이력 조회 (0~1개)
|
| 127 |
+
|
| 128 |
+
Tier 4 (대응 권고):
|
| 129 |
+
- search_queries: SOP·표준 절차 검색 (1~3개)
|
| 130 |
+
- incident_symptoms: 과거 해결책 조회 (0~2개)
|
| 131 |
+
- equipment_ids: PM 윈도우 조회 (1개, immediate 조치의 실행 가능 시점)
|
| 132 |
+
|
| 133 |
+
[routing 결정]
|
| 134 |
+
- action:
|
| 135 |
+
- proceed_full (대부분, 표준 Tier 2 → 3 → 4)
|
| 136 |
+
- fast_track (단일 원인 80%+ 우세 시 - Tier 3 LLM skip)
|
| 137 |
+
- escalate (고위험·다대수 영향 - 정상 진행 + human review 플래그)
|
| 138 |
+
- severity: low / medium / high / critical
|
| 139 |
+
|
| 140 |
+
[중요 원칙]
|
| 141 |
+
- 알람과 Tier 1을 보고 가장 정보가치 큰 쿼리/조회만 선별 (불필요한 호출 제거)
|
| 142 |
+
- search_queries는 도메인 용어를 풍부하게 (예: "Photo CD 산포 렌즈 오염 헤이즈")
|
| 143 |
+
- Tier 2와 Tier 4의 search_queries는 목적이 다름:
|
| 144 |
+
- Tier 2: 원인 후보 탐색용
|
| 145 |
+
- Tier 4: SOP·조치 절차 탐색용
|
| 146 |
+
- reasoning은 한 문장으로 plan의 핵심 의도 명시"""
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _build_user_prompt(alarm: dict, tier1: Tier1) -> str:
|
| 150 |
+
sensors = ", ".join(f["name"] for f in tier1["features"])
|
| 151 |
+
equipment_id = ALARM_EQUIPMENT.get(alarm["id"], "(미매핑)")
|
| 152 |
+
process = alarm["title"].split()[0]
|
| 153 |
+
return f"""## 이상 알람
|
| 154 |
+
- 공정: {alarm['title']} (current_stage: {process})
|
| 155 |
+
- lot: {alarm['lot_id']}
|
| 156 |
+
- 이상 피처: {alarm.get('feature')} {alarm.get('feature_arrow') or ''}
|
| 157 |
+
- 알람 ID: {alarm['id']}
|
| 158 |
+
- 추정 장비 ID: {equipment_id}
|
| 159 |
+
|
| 160 |
+
## Tier 1 이상 탐지 결과
|
| 161 |
+
- 이상 점수: {tier1['score']}
|
| 162 |
+
- 기여 센서(Top): {sensors}
|
| 163 |
+
|
| 164 |
+
위 알람의 전체 워크플로우(Tier 2→3→4) plan을 산출하세요."""
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@traceable(name="Planner_Agent", run_type="chain")
|
| 168 |
+
def plan_workflow(alarm: dict, tier1: Tier1) -> dict:
|
| 169 |
+
"""알람 + Tier 1을 보고 전체 워크플로우 plan을 한 번에 산출
|
| 170 |
+
|
| 171 |
+
반환: PLAN_SCHEMA 형식 dict (tier2/tier3/tier4 + action/severity/reasoning)
|
| 172 |
+
"""
|
| 173 |
+
resp = client().chat.completions.create(
|
| 174 |
+
model=PLANNER_MODEL,
|
| 175 |
+
messages=[
|
| 176 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 177 |
+
{"role": "user", "content": _build_user_prompt(alarm, tier1)},
|
| 178 |
+
],
|
| 179 |
+
response_format={
|
| 180 |
+
"type": "json_schema",
|
| 181 |
+
"json_schema": {"name": "plan", "schema": PLAN_SCHEMA, "strict": True},
|
| 182 |
+
},
|
| 183 |
+
)
|
| 184 |
+
return json.loads(resp.choices[0].message.content)
|
agents/response.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
"""Tier 4 대응 권고 에이전트
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
| 5 |
|
| 6 |
가용 도구: search_knowledge, lookup_incident_history, get_pm_history, check_pm_schedule
|
| 7 |
"""
|
|
@@ -116,10 +117,111 @@ def _initial_user_prompt(alarm: dict, tier1: Tier1, tier2: Tier2, tier3: Tier3)
|
|
| 116 |
필요한 SOP·과거 해결책·PM 윈도우는 도구를 호출해 자율적으로 수집하세요."""
|
| 117 |
|
| 118 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
@traceable(name="Tier4_Response_Agent", run_type="chain")
|
| 120 |
def run_response(
|
| 121 |
-
alarm: dict, tier1: Tier1, tier2: Tier2, tier3: Tier3,
|
|
|
|
|
|
|
| 122 |
) -> Tier4:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
messages = [
|
| 124 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 125 |
{"role": "user", "content": _initial_user_prompt(alarm, tier1, tier2, tier3)},
|
|
@@ -176,6 +278,7 @@ def run_response(
|
|
| 176 |
trace["tool_calls"] = tool_call_log
|
| 177 |
trace["iterations"] = iterations
|
| 178 |
trace["llm_calls"] = iterations + 1
|
|
|
|
| 179 |
|
| 180 |
return {
|
| 181 |
"immediate": llm_out["immediate"],
|
|
|
|
| 1 |
+
"""Tier 4 대응 권고 에이전트
|
| 2 |
|
| 3 |
+
두 모드 지원:
|
| 4 |
+
1. Autonomous (plan=None): LLM이 tool을 자율 호출하는 agent loop
|
| 5 |
+
2. Conductor (plan 제공): Planner가 지정한 tool 호출 + 단일 LLM synthesis
|
| 6 |
|
| 7 |
가용 도구: search_knowledge, lookup_incident_history, get_pm_history, check_pm_schedule
|
| 8 |
"""
|
|
|
|
| 117 |
필요한 SOP·과거 해결책·PM 윈도우는 도구를 호출해 자율적으로 수집하세요."""
|
| 118 |
|
| 119 |
|
| 120 |
+
CONDUCTOR_SYSTEM_PROMPT = """당신은 반도체 공정 대응 권고 전문가입니다.
|
| 121 |
+
Central Planner가 이미 필요한 정보(SOP·과거 해결책·PM 윈도우)를 모두 수집해 [수집된 컨텍스트]에 정리해 두었습니다.
|
| 122 |
+
당신은 추가 도구 호출 없이 그 컨텍스트만 사용해 산출하세요.
|
| 123 |
+
|
| 124 |
+
[최종 산출물]
|
| 125 |
+
- immediate: 즉시 조치 2~3건 (수 시간 내 실행 가능, meta에 시간·hold 대상·부서 명시)
|
| 126 |
+
- longterm: 중장기 조치 1~2건
|
| 127 |
+
- ref_doc_ids: 권고 근거로 실제 사용한 문서 ID (search_knowledge가 반환한 doc_id만)"""
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _execute_tier4_plan(plan_tier4: dict, trace_calls: list) -> tuple[str, list[str]]:
|
| 131 |
+
"""Planner가 지정한 tool들을 직접 호출, 컨텍스트 + 검색 doc_id 리스트 반환"""
|
| 132 |
+
blocks = []
|
| 133 |
+
found_docs: list[str] = []
|
| 134 |
+
for query in plan_tier4.get("search_queries", []):
|
| 135 |
+
r = dispatch_tool("search_knowledge", {"query": query})
|
| 136 |
+
trace_calls.append({"name": "search_knowledge", "args": {"query": query}})
|
| 137 |
+
blocks.append(f"[search_knowledge: {query!r}]\n{r}")
|
| 138 |
+
try:
|
| 139 |
+
parsed = json.loads(r)
|
| 140 |
+
found_docs.extend(h["doc_id"] for h in parsed.get("hits", []))
|
| 141 |
+
except (json.JSONDecodeError, KeyError):
|
| 142 |
+
pass
|
| 143 |
+
for symptom in plan_tier4.get("incident_symptoms", []):
|
| 144 |
+
r = dispatch_tool("lookup_incident_history", {"symptom": symptom})
|
| 145 |
+
trace_calls.append({"name": "lookup_incident_history", "args": {"symptom": symptom}})
|
| 146 |
+
blocks.append(f"[lookup_incident_history: {symptom!r}]\n{r}")
|
| 147 |
+
for eq_id in plan_tier4.get("equipment_ids", []):
|
| 148 |
+
r1 = dispatch_tool("get_pm_history", {"equipment_id": eq_id})
|
| 149 |
+
trace_calls.append({"name": "get_pm_history", "args": {"equipment_id": eq_id}})
|
| 150 |
+
blocks.append(f"[get_pm_history: {eq_id!r}]\n{r1}")
|
| 151 |
+
r2 = dispatch_tool("check_pm_schedule", {"equipment_id": eq_id})
|
| 152 |
+
trace_calls.append({"name": "check_pm_schedule", "args": {"equipment_id": eq_id}})
|
| 153 |
+
blocks.append(f"[check_pm_schedule: {eq_id!r}]\n{r2}")
|
| 154 |
+
return "\n\n".join(blocks) if blocks else "(planner가 정보 수집 지시 없음)", found_docs
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _run_response_conductor(
|
| 158 |
+
alarm: dict, tier1: Tier1, tier2: Tier2, tier3: Tier3,
|
| 159 |
+
plan: dict, trace: dict | None,
|
| 160 |
+
) -> Tier4:
|
| 161 |
+
tool_log: list[dict] = []
|
| 162 |
+
knowledge, found_docs = _execute_tier4_plan(plan.get("tier4", {}), tool_log)
|
| 163 |
+
|
| 164 |
+
cause_lines = "\n".join(f"- {c['name']} ({c['pct']}%)" for c in tier2["causes"])
|
| 165 |
+
impact_lots_text = ", ".join(
|
| 166 |
+
f"{l['label']} {l['lots']}lot/{l['wafers']}장" for l in tier3["impact_lots"]
|
| 167 |
+
)
|
| 168 |
+
user_prompt = f"""## 이상 알람
|
| 169 |
+
- 공정: {alarm['title']}, lot: {alarm['lot_id']}
|
| 170 |
+
|
| 171 |
+
## Tier 1: 이상 점수 {tier1['score']}
|
| 172 |
+
|
| 173 |
+
## Tier 2 원인 (기여도 순)
|
| 174 |
+
{cause_lines}
|
| 175 |
+
|
| 176 |
+
## Tier 3 영향
|
| 177 |
+
- 예상 수율 손실: {tier3['yield_loss']} %p
|
| 178 |
+
- 영향 WIP: {impact_lots_text}
|
| 179 |
+
|
| 180 |
+
## 수집된 컨텍스트 (Planner 지정)
|
| 181 |
+
{knowledge}
|
| 182 |
+
|
| 183 |
+
위 컨텍스트만 사용해 immediate, longterm, ref_doc_ids를 산출하세요."""
|
| 184 |
+
|
| 185 |
+
resp = client().chat.completions.create(
|
| 186 |
+
model=SUBAGENT_MODEL,
|
| 187 |
+
messages=[
|
| 188 |
+
{"role": "system", "content": CONDUCTOR_SYSTEM_PROMPT},
|
| 189 |
+
{"role": "user", "content": user_prompt},
|
| 190 |
+
],
|
| 191 |
+
response_format={
|
| 192 |
+
"type": "json_schema",
|
| 193 |
+
"json_schema": {"name": "tier4_part", "schema": LLM_PART_SCHEMA, "strict": True},
|
| 194 |
+
},
|
| 195 |
+
)
|
| 196 |
+
llm_out = json.loads(resp.choices[0].message.content)
|
| 197 |
+
|
| 198 |
+
ref_ids = llm_out.get("ref_doc_ids") or found_docs[:4]
|
| 199 |
+
refs = [{"id": d, "desc": _doc_description(d)} for d in ref_ids if d]
|
| 200 |
+
|
| 201 |
+
if trace is not None:
|
| 202 |
+
trace["tool_calls"] = tool_log
|
| 203 |
+
trace["iterations"] = 0
|
| 204 |
+
trace["llm_calls"] = 1
|
| 205 |
+
trace["mode"] = "conductor"
|
| 206 |
+
|
| 207 |
+
return {
|
| 208 |
+
"immediate": llm_out["immediate"],
|
| 209 |
+
"longterm": llm_out["longterm"],
|
| 210 |
+
"refs": refs,
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
@traceable(name="Tier4_Response_Agent", run_type="chain")
|
| 215 |
def run_response(
|
| 216 |
+
alarm: dict, tier1: Tier1, tier2: Tier2, tier3: Tier3,
|
| 217 |
+
trace: dict | None = None,
|
| 218 |
+
plan: dict | None = None,
|
| 219 |
) -> Tier4:
|
| 220 |
+
"""Tier 4 대응 권고. plan 제공 시 conductor 모드(LLM 1회), 아니면 autonomous loop."""
|
| 221 |
+
if plan is not None:
|
| 222 |
+
return _run_response_conductor(alarm, tier1, tier2, tier3, plan, trace)
|
| 223 |
+
|
| 224 |
+
# autonomous 모드 (LLM이 tool을 자율 호출하는 기존 loop)
|
| 225 |
messages = [
|
| 226 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 227 |
{"role": "user", "content": _initial_user_prompt(alarm, tier1, tier2, tier3)},
|
|
|
|
| 278 |
trace["tool_calls"] = tool_call_log
|
| 279 |
trace["iterations"] = iterations
|
| 280 |
trace["llm_calls"] = iterations + 1
|
| 281 |
+
trace["mode"] = "autonomous"
|
| 282 |
|
| 283 |
return {
|
| 284 |
"immediate": llm_out["immediate"],
|