hee_!J commited on
Commit ·
3fb690f
1
Parent(s): aab1147
feat(conductor): Plan-and-Execute 패턴 - Central Planner + Tier executor (env AGENT_MODE)
Browse filesFiles changed (5)
- agents/cause.py+90-12
- agents/impact.py+102-4
- agents/orchestrator.py+127-80
- agents/planner.pyAdded+184
- agents/response.py+107-4
1234567891011121380 unmodified lines94959697989910010110210310410510610710845 unmodified lines154155156157158"""Tier 2 원인 분석 에이전트 (Agentic RAG)LLM이 도구를 자율 호출해 컨텍스트를 수집한 뒤 원인을 추정합니다.가용 도구: search_knowledge, lookup_incident_history, get_pm_history흐름:1. system prompt + 알람·Tier1 컨텍스트로 시작 (사전 retrieval 없음)2. tool-calling loop: LLM이 필요한 도구를 호출 -> 결과를 컨텍스트에 추가3. LLM이 더 호출하지 않을 때(또는 MAX_ITER 도달) synthesis 호출4. response_format=json_schema 로 TIER2_SCHEMA 구조화 출력"""import json80 unmodified linesreturn out@traceable(name="Tier2_Cause_Agent", run_type="chain")def run_cause(alarm: dict, tier1: Tier1, trace: dict | None = None, retry_hint: bool = False) -> Tier2:"""원인 분석을 agentic RAG로 실행retry_hint=True 면 직전 분석의 기여도가 낮았다는 신호를 prompt에 추가해더 적극적으로 도구를 호출하도록 유도 (orchestrator의 confidence retry용)"""user_prompt = _initial_user_prompt(alarm, tier1)if retry_hint:user_prompt += (45 unmodified linestrace["tool_calls"] = tool_call_logtrace["iterations"] = iterationstrace["llm_calls"] = iterations + 1return result12345678910111280 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418545 unmodified lines231232233234235236"""Tier 2 원인 분석 에이전트두 모드 지원:1. **Autonomous (기본, plan=None)**: LLM이 tool을 자율 호출하는 agent loop- 2~3 iteration + synthesis = LLM 호출 3~4회2. **Conductor (plan 제공)**: Planner가 지정한 tool 호출 + 단일 LLM synthesis- Tool 직접 실행 + LLM 호출 1회. 재귀·loop 없음가용 도구: search_knowledge, lookup_incident_history, get_pm_history"""import json80 unmodified linesreturn outCONDUCTOR_SYSTEM_PROMPT = """당신은 반도체 공정 원인 분석 전문가입니다.Central Planner가 이미 필요한 정보를 모두 수집해 [수집된 컨텍스트]에 정리해 두었습니다.당신은 추가 도구 호출 없이 그 컨텍스트만 사용해 원인 2~3개를 산출하세요.[최종 산출물]- causes: 2~3개. 각 원인은 name / pct(기여도 %) / evidence(구체적 근거) / citations(문서 ID 또는 incident ID)- pct 합은 100에 가까워야 함, 기여도 높은 원인부터 정렬- 제공되지 않은 정보는 인용하지 마세요"""def _execute_tier2_plan(plan_tier2: dict, trace_calls: list) -> str:"""Planner가 지정한 tool들을 직접 호출하고 컨텍스트로 변환"""blocks = []for query in plan_tier2.get("search_queries", []):result = dispatch_tool("search_knowledge", {"query": query})trace_calls.append({"name": "search_knowledge", "args": {"query": query}})blocks.append(f"[search_knowledge: {query!r}]\n{result}")for symptom in plan_tier2.get("incident_symptoms", []):result = dispatch_tool("lookup_incident_history", {"symptom": symptom})trace_calls.append({"name": "lookup_incident_history", "args": {"symptom": symptom}})blocks.append(f"[lookup_incident_history: {symptom!r}]\n{result}")for eq_id in plan_tier2.get("equipment_ids", []):result = dispatch_tool("get_pm_history", {"equipment_id": eq_id})trace_calls.append({"name": "get_pm_history", "args": {"equipment_id": eq_id}})blocks.append(f"[get_pm_history: {eq_id!r}]\n{result}")return "\n\n".join(blocks) if blocks else "(planner가 정보 수집 지시 없음)"def _run_cause_conductor(alarm: dict, tier1: Tier1, plan: dict, trace: dict | None) -> Tier2:"""Conductor 모드: plan대로 tool 실행 + 1회 LLM synthesis"""tool_log: list[dict] = []knowledge = _execute_tier2_plan(plan.get("tier2", {}), tool_log)sensors = ", ".join(f["name"] for f in tier1["features"])user_prompt = f"""## 이상 알람- 공정: {alarm['title']}- lot: {alarm['lot_id']}- 이상 피처: {alarm.get('feature')} {alarm.get('feature_arrow') or ''}## Tier 1 이상 탐지 결과- 이상 점수: {tier1['score']}- 기여 센서(Top): {sensors}## 수집된 컨텍스트 (Planner 지정){knowledge}위 컨텍스트만 사용해 원인을 분석하세요."""resp = client().chat.completions.create(model=SUBAGENT_MODEL,messages=[{"role": "system", "content": CONDUCTOR_SYSTEM_PROMPT},{"role": "user", "content": user_prompt},],response_format={"type": "json_schema","json_schema": {"name": "tier2", "schema": TIER2_SCHEMA, "strict": True},},)result = json.loads(resp.choices[0].message.content)if trace is not None:trace["tool_calls"] = tool_logtrace["iterations"] = 0trace["llm_calls"] = 1trace["mode"] = "conductor"return result@traceable(name="Tier2_Cause_Agent", run_type="chain")def run_cause(alarm: dict,tier1: Tier1,trace: dict | None = None,retry_hint: bool = False,plan: dict | None = None,) -> Tier2:"""원인 분석 실행plan 제공 시 conductor 모드 (단일 LLM 호출, tool 직접 실행).plan=None이면 기존 autonomous tool-calling loop 모드.retry_hint=True 면 autonomous 모드에서 더 적극적으로 도구를 호출하도록 유도."""if plan is not None:return _run_cause_conductor(alarm, tier1, plan, trace)user_prompt = _initial_user_prompt(alarm, tier1)if retry_hint:user_prompt += (45 unmodified linestrace["tool_calls"] = tool_call_logtrace["iterations"] = iterationstrace["llm_calls"] = iterations + 1trace["mode"] = "autonomous"return result
123456779 unmodified lines878889909192939446 unmodified lines141142143144145146"""Tier 3 공정 간 영향 평가 에이전트 (tool-using agent)LLM이 도구를 자율 호출해 WIP·downstream·yield 기준선·PM 이력을 모은 뒤yield_loss와 영향 받는 후공정 목록을 산출합니다.가용 도구: query_wip_status, get_downstream_steps, get_yield_baseline, get_pm_history"""79 unmodified linesWIP·downstream·yield·PM 컨텍스트는 도구를 호출해 자율적으로 수집하세요."""@traceable(name="Tier3_Impact_Agent", run_type="chain")def run_impact(alarm: dict, tier1: Tier1, tier2: Tier2, trace: dict | None = None) -> Tier3:messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": _initial_user_prompt(alarm, tier1, tier2)},46 unmodified linestrace["tool_calls"] = tool_call_logtrace["iterations"] = iterationstrace["llm_calls"] = iterations + 1return {"yield_loss": round(float(llm_out["yield_loss"]), 1),1234567879 unmodified lines88899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019146 unmodified lines238239240241242243244"""Tier 3 공정 간 영향 평가 에이전트두 모드 지원:1. Autonomous (plan=None): LLM이 tool을 자율 호출하는 agent loop2. Conductor (plan 제공): Planner가 지정한 tool 호출 + 단일 LLM synthesis가용 도구: query_wip_status, get_downstream_steps, get_yield_baseline, get_pm_history"""79 unmodified linesWIP·downstream·yield·PM 컨텍스트는 도구를 호출해 자율적으로 수집하세요."""CONDUCTOR_SYSTEM_PROMPT = """당신은 반도체 공정 영향 평가 전문가입니다.Central Planner가 이미 필요한 정보(WIP·downstream·yield·PM)를 모두 수집해 [수집된 컨텍스트]에 정리해 두었습니다.당신은 추가 도구 호출 없이 그 컨텍스트만 사용해 산출하세요.[최종 산출물]- yield_loss: 본 이상으로 인한 예상 수율 손실(%p, 소수 한 자리)- downstream_dependencies: 영향 받는 후공정 (current 제외) - stage / delta / tag / kind"""def _execute_tier3_plan(plan_tier3: dict, trace_calls: list) -> str:"""Planner가 지정한 tool들을 직접 호출하고 컨텍스트로 변환"""blocks = []if plan_tier3.get("alarm_id"):r = dispatch_tool("query_wip_status", {"alarm_id": plan_tier3["alarm_id"]})trace_calls.append({"name": "query_wip_status", "args": {"alarm_id": plan_tier3["alarm_id"]}})blocks.append(f"[query_wip_status: {plan_tier3['alarm_id']!r}]\n{r}")for stage in plan_tier3.get("downstream_stages", []):r = dispatch_tool("get_downstream_steps", {"current_stage": stage})trace_calls.append({"name": "get_downstream_steps", "args": {"current_stage": stage}})blocks.append(f"[get_downstream_steps: {stage!r}]\n{r}")for proc in plan_tier3.get("yield_processes", []):r = dispatch_tool("get_yield_baseline", {"process": proc})trace_calls.append({"name": "get_yield_baseline", "args": {"process": proc}})blocks.append(f"[get_yield_baseline: {proc!r}]\n{r}")for eq_id in plan_tier3.get("equipment_ids", []):r = dispatch_tool("get_pm_history", {"equipment_id": eq_id})trace_calls.append({"name": "get_pm_history", "args": {"equipment_id": eq_id}})blocks.append(f"[get_pm_history: {eq_id!r}]\n{r}")return "\n\n".join(blocks) if blocks else "(planner가 정보 수집 지시 없음)"def _run_impact_conductor(alarm: dict, tier1: Tier1, tier2: Tier2, plan: dict, trace: dict | None) -> Tier3:tool_log: list[dict] = []knowledge = _execute_tier3_plan(plan.get("tier3", {}), tool_log)cause_lines = "\n".join(f"- {c['name']} ({c['pct']}%): {c['evidence'][:120]}" for c in tier2["causes"])current_stage = _stage_from_alarm(alarm)user_prompt = f"""## 이상 알람- 공정: {alarm['title']} (current_stage: {current_stage})## Tier 1: 이상 점수 {tier1['score']}## Tier 2 원인 분석{cause_lines}## 수집된 컨텍스트 (Planner 지정){knowledge}위 컨텍스트만 사용해 yield_loss와 downstream_dependencies를 산출하세요."""resp = client().chat.completions.create(model=SUBAGENT_MODEL,messages=[{"role": "system", "content": CONDUCTOR_SYSTEM_PROMPT},{"role": "user", "content": user_prompt},],response_format={"type": "json_schema","json_schema": {"name": "tier3_part", "schema": LLM_PART_SCHEMA, "strict": True},},)llm_out = json.loads(resp.choices[0].message.content)current_dep = {"stage": current_stage,"delta": f"+{tier1['score']}","tag": "현재","kind": "current",}if trace is not None:trace["tool_calls"] = tool_logtrace["iterations"] = 0trace["llm_calls"] = 1trace["mode"] = "conductor"return {"yield_loss": round(float(llm_out["yield_loss"]), 1),"dependencies": [current_dep] + llm_out["downstream_dependencies"],"impact_lots": get_affected_wip(alarm["id"]),}@traceable(name="Tier3_Impact_Agent", run_type="chain")def run_impact(alarm: dict,tier1: Tier1,tier2: Tier2,trace: dict | None = None,plan: dict | None = None,) -> Tier3:"""Tier 3 영향 평가. plan 제공 시 conductor 모드(LLM 1회), 아니면 autonomous loop."""if plan is not None:return _run_impact_conductor(alarm, tier1, tier2, plan, trace)messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": _initial_user_prompt(alarm, tier1, tier2)},46 unmodified linestrace["tool_calls"] = tool_call_logtrace["iterations"] = iterationstrace["llm_calls"] = iterations + 1trace["mode"] = "autonomous"return {"yield_loss": round(float(llm_out["yield_loss"]), 1),
1234567891011121314151617181920212223243 unmodified lines2829303132334 unmodified lines3839404142432 unmodified lines464748495051521 unmodified line545556575859605 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161175 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661678 unmodified lines176177178179180181182"""4-Tier 멀티에이전트 오케스트레이터 (LangGraph 기반)각 Tier가 tool-using LLM agent이며, LangGraph로 조정합니다.[그래프 구조]START -> detectdetect --(score >= 0.3)--> causedetect --(score < 0.3)---> noise -> END (severity gate)cause --(max pct < 40)---> cause_retry -> supervisorcause --(max pct >= 40)--> supervisorsupervisor --(LLM 결정)-+-> impact -> response -> END (proceed_full / escalate)+-> fast_impact -> response -> END (fast_track: Tier 3 skip)Supervisor (`agents.supervisor`)는 LLM이 Tier 2 결과를 보고 동적으로 routing 결정.- proceed_full: 표준 (Tier 3 + 4)- fast_track: 원인 단독 우세 시 Tier 3 skip- escalate: 고위험 - 정상 진행 + human review 플래그 (tier4.metadata에 기록)[캐싱] build_graph 1회 컴파일, run_orchestrator 알람당 8개 LRU[Observability] @traceable + wrap_openai (환경변수 LANGSMITH_TRACING=true 시 활성)"""from functools import lru_cachefrom typing import TypedDict3 unmodified linesfrom agents.cause import run_causefrom agents.detection import run_detectionfrom agents.impact import run_impactfrom agents.response import run_responsefrom agents.supervisor import run_supervisorfrom core.schema import Tier1, Tier2, Tier3, Tier4, TierData4 unmodified linesCAUSE_CONFIDENCE_THRESHOLD = 40class _GraphState(TypedDict, total=False):alarm: dicttier1: Tier12 unmodified linestier4: Tier4skipped: boolcause_retried: boolsupervisor_decision: dict # {action, severity, reasoning}def _node_detect(state: _GraphState) -> dict:1 unmodified linedef _route_after_detect(state: _GraphState) -> str:return "cause" if state["tier1"]["score"] >= SEVERITY_THRESHOLD else "noise"def _node_noise(state: _GraphState) -> dict:5 unmodified lines}def _node_cause(state: _GraphState) -> dict:return {"tier2": run_cause(state["alarm"], state["tier1"])}def _route_after_cause(state: _GraphState) -> str:if state.get("cause_retried"):return "supervisor" # 이미 재시도 - supervisor로 직행causes = state["tier2"]["causes"]max_pct = max((c.get("pct", 0) for c in causes), default=0)return "cause_retry" if max_pct < CAUSE_CONFIDENCE_THRESHOLD else "supervisor"def _node_cause_retry(state: _GraphState) -> dict:return {"tier2": run_cause(state["alarm"], state["tier1"], retry_hint=True),"cause_retried": True,}def _node_supervisor(state: _GraphState) -> dict:decision = run_supervisor(state["alarm"], state["tier1"], state["tier2"])return {"supervisor_decision": decision}def _route_after_supervisor(state: _GraphState) -> str:action = state["supervisor_decision"]["action"]if action == "fast_track":return "fast_impact"return "impact" # proceed_full + escalate 모두 impact 경유def _node_impact(state: _GraphState) -> dict:return {"tier3": run_impact(state["alarm"], state["tier1"], state["tier2"])}def _node_fast_impact(state: _GraphState) -> dict:"""fast_track: LLM 호출 없이 결정론적 lightweight impactTier 4가 tier3을 요구하므로 최소 정보만 채워 전달.yield_loss는 tier1 score를 단순 변환, downstream은 current stage만."""alarm = state["alarm"]tier1 = state["tier1"]return {"tier3": {"yield_loss": round(float(tier1["score"]) * 3.0, 1), # 단순 추정"dependencies": [{"stage": alarm["title"].split()[0],"delta": f"+{tier1['score']}",5 unmodified lines}def _node_response(state: _GraphState) -> dict:tier4 = run_response(state["alarm"], state["tier1"], state["tier2"], state["tier3"])# supervisor가 escalate 결정 시 immediate 첫 항목에 human review 플래그 추가decision = state.get("supervisor_decision", {})if decision.get("action") == "escalate" and tier4.get("immediate"):tier4["immediate"][0]["text"] = "🚨 [HUMAN REVIEW 요구] " + tier4["immediate"][0]["text"]return {"tier4": tier4}@lru_cache(maxsize=1)def build_graph():g = StateGraph(_GraphState)g.add_node("detect", _node_detect)g.add_node("noise", _node_noise)g.add_node("cause", _node_cause)g.add_node("cause_retry", _node_cause_retry)g.add_node("supervisor", _node_supervisor)g.add_node("impact", _node_impact)g.add_node("fast_impact", _node_fast_impact)g.add_node("response", _node_response)g.add_edge(START, "detect")g.add_conditional_edges("detect", _route_after_detect, {"cause": "cause","noise": "noise",})g.add_edge("noise", END)g.add_conditional_edges("cause", _route_after_cause, {"supervisor": "supervisor","cause_retry": "cause_retry",})g.add_edge("cause_retry", "supervisor")g.add_conditional_edges("supervisor", _route_after_supervisor, {"impact": "impact","fast_impact": "fast_impact",})g.add_edge("impact", "response")g.add_edge("fast_impact", "response")g.add_edge("response", END)return g.compile()8 unmodified lines@lru_cache(maxsize=8)def run_orchestrator(alarm_id: str) -> TierData:alarm = _find_alarm(alarm_id)graph = build_graph()final = graph.invoke({"alarm": alarm})return {"tier1": final["tier1"],12345678910111213141516171819202122232425263 unmodified lines303132333435364 unmodified lines414243444546474849502 unmodified lines53545556575859601 unmodified line626364656667685 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061075 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132148 unmodified lines223224225226227228229"""4-Tier 멀티에이전트 오케스트레이터 (LangGraph 기반)두 가지 실행 모드 지원 (환경변수 AGENT_MODE):- **conductor** (기본): Central Planner Agent가 전체 plan 1회 산출각 Tier executor가 plan대로 tool 호출 + LLM 1회 synthesis→ LLM 호출 ~70% 감소, latency 큰 폭 단축- **autonomous**: 각 Tier가 tool-using agent loop로 자율 실행→ 적응성 높으나 LLM 호출 많음[그래프 - conductor 모드]START → detect → (severity gate) → planner → (action 분기)↓+→ cause → impact → response → END (proceed_full)+→ cause → fast_impact → response → END (fast_track)+→ cause → impact → response_escalate → END (escalate, T4에 🚨 prepend)[그래프 - autonomous 모드]기존 구조 (severity gate + cause_retry + supervisor 분기)알람 dict은 data.demo.DEFAULT_ALARMS에서 ID로 조회.@traceable (LangSmith) + wrap_openai 로 LLM·tool 호출 자동 트레이스."""import osfrom functools import lru_cachefrom typing import TypedDict3 unmodified linesfrom agents.cause import run_causefrom agents.detection import run_detectionfrom agents.impact import run_impactfrom agents.planner import plan_workflowfrom agents.response import run_responsefrom agents.supervisor import run_supervisorfrom core.schema import Tier1, Tier2, Tier3, Tier4, TierData4 unmodified linesCAUSE_CONFIDENCE_THRESHOLD = 40def _agent_mode() -> str:return os.getenv("AGENT_MODE", "conductor").lower()class _GraphState(TypedDict, total=False):alarm: dicttier1: Tier12 unmodified linestier4: Tier4skipped: boolcause_retried: boolsupervisor_decision: dictplan: dict # conductor 모드의 Planner 결과def _node_detect(state: _GraphState) -> dict:1 unmodified linedef _route_after_detect(state: _GraphState) -> str:return "go" if state["tier1"]["score"] >= SEVERITY_THRESHOLD else "noise"def _node_noise(state: _GraphState) -> dict:5 unmodified lines}# ==================== Conductor 모드 노드 ====================def _node_planner(state: _GraphState) -> dict:return {"plan": plan_workflow(state["alarm"], state["tier1"])}def _route_after_planner(state: _GraphState) -> str:action = state["plan"].get("action", "proceed_full")if action == "fast_track":return "fast_track"return "proceed" # proceed_full + escalate 모두 표준 경로def _node_cause_conductor(state: _GraphState) -> dict:return {"tier2": run_cause(state["alarm"], state["tier1"], plan=state["plan"])}def _node_impact_conductor(state: _GraphState) -> dict:return {"tier3": run_impact(state["alarm"], state["tier1"], state["tier2"], plan=state["plan"])}def _node_fast_impact(state: _GraphState) -> dict:"""fast_track: deterministic 경량 처리 (LLM 호출 없음)"""alarm = state["alarm"]tier1 = state["tier1"]return {"tier3": {"yield_loss": round(float(tier1["score"]) * 3.0, 1),"dependencies": [{"stage": alarm["title"].split()[0],"delta": f"+{tier1['score']}",5 unmodified lines}def _node_response_conductor(state: _GraphState) -> dict:tier4 = run_response(state["alarm"], state["tier1"], state["tier2"], state["tier3"], plan=state["plan"])if state["plan"].get("action") == "escalate" and tier4.get("immediate"):tier4["immediate"][0]["text"] = "🚨 [HUMAN REVIEW 요구] " + tier4["immediate"][0]["text"]return {"tier4": tier4}# ==================== Autonomous 모드 노드 (기존 보존) ====================def _node_cause_autonomous(state: _GraphState) -> dict:return {"tier2": run_cause(state["alarm"], state["tier1"])}def _route_after_cause_autonomous(state: _GraphState) -> str:if state.get("cause_retried"):return "supervisor"causes = state["tier2"]["causes"]max_pct = max((c.get("pct", 0) for c in causes), default=0)return "cause_retry" if max_pct < CAUSE_CONFIDENCE_THRESHOLD else "supervisor"def _node_cause_retry(state: _GraphState) -> dict:return {"tier2": run_cause(state["alarm"], state["tier1"], retry_hint=True),"cause_retried": True,}def _node_supervisor(state: _GraphState) -> dict:return {"supervisor_decision": run_supervisor(state["alarm"], state["tier1"], state["tier2"])}def _route_after_supervisor(state: _GraphState) -> str:return "fast_track" if state["supervisor_decision"]["action"] == "fast_track" else "proceed"def _node_impact_autonomous(state: _GraphState) -> dict:return {"tier3": run_impact(state["alarm"], state["tier1"], state["tier2"])}def _node_response_autonomous(state: _GraphState) -> dict:tier4 = run_response(state["alarm"], state["tier1"], state["tier2"], state["tier3"])decision = state.get("supervisor_decision", {})if decision.get("action") == "escalate" and tier4.get("immediate"):tier4["immediate"][0]["text"] = "🚨 [HUMAN REVIEW 요구] " + tier4["immediate"][0]["text"]return {"tier4": tier4}# ==================== Graph 빌더 ====================@lru_cache(maxsize=2)def build_graph(mode: str = "conductor"):g = StateGraph(_GraphState)g.add_node("detect", _node_detect)g.add_node("noise", _node_noise)g.add_edge(START, "detect")g.add_edge("noise", END)if mode == "conductor":g.add_node("planner", _node_planner)g.add_node("cause", _node_cause_conductor)g.add_node("impact", _node_impact_conductor)g.add_node("fast_impact", _node_fast_impact)g.add_node("response", _node_response_conductor)g.add_conditional_edges("detect", _route_after_detect, {"go": "planner", "noise": "noise"})g.add_edge("planner", "cause")g.add_conditional_edges("cause", _route_after_planner, {"proceed": "impact","fast_track": "fast_impact",})g.add_edge("impact", "response")g.add_edge("fast_impact", "response")g.add_edge("response", END)else:# autonomous (기존 구조)g.add_node("cause", _node_cause_autonomous)g.add_node("cause_retry", _node_cause_retry)g.add_node("supervisor", _node_supervisor)g.add_node("impact", _node_impact_autonomous)g.add_node("fast_impact", _node_fast_impact)g.add_node("response", _node_response_autonomous)g.add_conditional_edges("detect", _route_after_detect, {"go": "cause", "noise": "noise"})g.add_conditional_edges("cause", _route_after_cause_autonomous, {"supervisor": "supervisor","cause_retry": "cause_retry",})g.add_edge("cause_retry", "supervisor")g.add_conditional_edges("supervisor", _route_after_supervisor, {"proceed": "impact","fast_track": "fast_impact",})g.add_edge("impact", "response")g.add_edge("fast_impact", "response")g.add_edge("response", END)return g.compile()8 unmodified lines@lru_cache(maxsize=8)def run_orchestrator(alarm_id: str) -> TierData:alarm = _find_alarm(alarm_id)graph = build_graph(_agent_mode())final = graph.invoke({"alarm": alarm})return {"tier1": final["tier1"],
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184"""Central Planner Agent (Plan-and-Execute pattern)
알람과 Tier 1 결과를 보고 전체 워크플로우 plan을 1회 LLM 호출로 산출합니다.각 Tier executor는 plan대로 도구를 직접 호출하고 LLM 1회로 결과를 합성합니다.
기존 autonomous tool-using loop 대비:- LLM 호출 ~70% 감소 (각 tier loop 제거)- 재귀/무한루프 위험 원천 차단 (LLM이 tool을 자율 선택하지 않음)- 통신 오버헤드 최소화 (synthesis context를 한 번에 구성)- 비용·latency 큰 폭 절감 (gpt-4o-mini로 planning + gpt-5-mini로 synthesis)
설계:- Planner가 구체적 함수 호출이 아닌 "필요한 정보 채널" (query/symptom/equipment_id 리스트)을 지정- 각 Tier executor가 그 채널을 받아 결정론적으로 tool 호출 (병렬 가능)- Tier executor는 단 1회 LLM 호출로 synthesis (tools 인자 없이)"""import json
from langsmith import traceable
from agents.llm import clientfrom agents.tools.equipment import ALARM_EQUIPMENTfrom core.schema import Tier1
PLANNER_MODEL = "gpt-4o-mini"
PLAN_SCHEMA = { "type": "object", "properties": { "tier2": { "type": "object", "properties": { "search_queries": { "type": "array", "items": {"type": "string"}, "description": "사내 지식 검색 쿼리 (1~3개)", }, "incident_symptoms": { "type": "array", "items": {"type": "string"}, "description": "과거 incident DB 조회용 증상 (0~2개)", }, "equipment_ids": { "type": "array", "items": {"type": "string"}, "description": "PM 이력 조회 장비 ID (0~1개)", }, }, "required": ["search_queries", "incident_symptoms", "equipment_ids"], "additionalProperties": False, }, "tier3": { "type": "object", "properties": { "alarm_id": {"type": "string", "description": "WIP 조회용 알람 ID"}, "downstream_stages": { "type": "array", "items": {"type": "string"}, "description": "후공정 의존성 조회 (1개)", }, "yield_processes": { "type": "array", "items": {"type": "string"}, "description": "yield baseline 조회 (1~2개)", }, "equipment_ids": { "type": "array", "items": {"type": "string"}, "description": "PM 이력 조회 장비 ID (0~1개)", }, }, "required": ["alarm_id", "downstream_stages", "yield_processes", "equipment_ids"], "additionalProperties": False, }, "tier4": { "type": "object", "properties": { "search_queries": { "type": "array", "items": {"type": "string"}, "description": "SOP 검색 쿼리 (1~3개)", }, "incident_symptoms": { "type": "array", "items": {"type": "string"}, "description": "과거 해결책 조회 (0~2개)", }, "equipment_ids": { "type": "array", "items": {"type": "string"}, "description": "PM 윈도우 조회 장비 ID (1개)", }, }, "required": ["search_queries", "incident_symptoms", "equipment_ids"], "additionalProperties": False, }, "action": { "type": "string", "enum": ["proceed_full", "fast_track", "escalate"], "description": "워크플로우 분기 (Tier 3 skip 여부, escalation 플래그)", }, "severity": { "type": "string", "enum": ["low", "medium", "high", "critical"], }, "reasoning": {"type": "string"}, }, "required": ["tier2", "tier3", "tier4", "action", "severity", "reasoning"], "additionalProperties": False,}
SYSTEM_PROMPT = """당신은 반도체 fab 인시던트 대응 시스템의 Central Planner Agent입니다.이상 알람과 Tier 1 탐지 결과를 받아 전체 워크플로우(Tier 2 원인분석 → Tier 3 영향평가 → Tier 4 대응권고)에 필요한 정보 수집 plan을 한 번에 산출합니다.
[가용 정보 채널 - tier별]
Tier 2 (원인 분석):- search_queries: 사내 지식(INC/FMEA/SOP/FLOW) hybrid 검색 (1~3개)- incident_symptoms: 과거 incident DB 구조화 조회 (0~2개)- equipment_ids: 장비 PM 이력 조회 (0~1개)
Tier 3 (영향 평가):- alarm_id: WIP 조회 (��드시 1개, 알람 ID 그대로)- downstream_stages: 후공정 의존성 (1개, 현재 공정명 - 예: "Photo", "Etch", "CMP")- yield_processes: yield baseline 조회 (1~2개)- equipment_ids: PM 이력 조회 (0~1개)
Tier 4 (대응 권고):- search_queries: SOP·표준 절차 검색 (1~3개)- incident_symptoms: 과거 해결책 조회 (0~2개)- equipment_ids: PM 윈도우 조회 (1개, immediate 조치의 실행 가능 시점)
[routing 결정]- action: - proceed_full (대부분, 표준 Tier 2 → 3 → 4) - fast_track (단일 원인 80%+ 우세 시 - Tier 3 LLM skip) - escalate (고위험·다대수 영향 - 정상 진행 + human review 플래그)- severity: low / medium / high / critical
[중요 원칙]- 알람과 Tier 1을 보고 가장 정보가치 큰 쿼리/조회만 선별 (불필요한 호출 제거)- search_queries는 도메인 용어를 풍부하게 (예: "Photo CD 산포 렌즈 오염 헤이즈")- Tier 2와 Tier 4의 search_queries는 목적이 다름: - Tier 2: 원인 후보 탐색용 - Tier 4: SOP·조치 절차 탐색용- reasoning은 한 문장으로 plan의 핵심 의도 명시"""
def _build_user_prompt(alarm: dict, tier1: Tier1) -> str: sensors = ", ".join(f["name"] for f in tier1["features"]) equipment_id = ALARM_EQUIPMENT.get(alarm["id"], "(미매핑)") process = alarm["title"].split()[0] return f"""## 이상 알람- 공정: {alarm['title']} (current_stage: {process})- lot: {alarm['lot_id']}- 이상 피처: {alarm.get('feature')} {alarm.get('feature_arrow') or ''}- 알람 ID: {alarm['id']}- 추정 장비 ID: {equipment_id}
## Tier 1 이상 탐지 결과- 이상 점수: {tier1['score']}- 기여 센서(Top): {sensors}
위 알람의 전체 워크플로우(Tier 2→3→4) plan을 산출하세요."""
@traceable(name="Planner_Agent", run_type="chain")def plan_workflow(alarm: dict, tier1: Tier1) -> dict: """알람 + Tier 1을 보고 전체 워크플로우 plan을 한 번에 산출
반환: PLAN_SCHEMA 형식 dict (tier2/tier3/tier4 + action/severity/reasoning) """ resp = client().chat.completions.create( model=PLANNER_MODEL, messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": _build_user_prompt(alarm, tier1)}, ], response_format={ "type": "json_schema", "json_schema": {"name": "plan", "schema": PLAN_SCHEMA, "strict": True}, }, ) return json.loads(resp.choices[0].message.content)1234567108 unmodified lines11611711811912012112212312412550 unmodified lines176177178179180181"""Tier 4 대응 권고 에이전트 (tool-using agent)LLM이 도구를 자율 호출해 SOP·과거 incident·PM 윈도우를 모은 뒤즉시 조치(immediate)와 중장기 조치(longterm)를 산출합니다.가용 도구: search_knowledge, lookup_incident_history, get_pm_history, check_pm_schedule"""108 unmodified lines필요한 SOP·과거 해결책·PM 윈도우는 도구를 호출해 자율적으로 수집하세요."""@traceable(name="Tier4_Response_Agent", run_type="chain")def run_response(alarm: dict, tier1: Tier1, tier2: Tier2, tier3: Tier3, trace: dict | None = None) -> Tier4:messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": _initial_user_prompt(alarm, tier1, tier2, tier3)},50 unmodified linestrace["tool_calls"] = tool_call_logtrace["iterations"] = iterationstrace["llm_calls"] = iterations + 1return {"immediate": llm_out["immediate"],12345678108 unmodified lines11711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622750 unmodified lines278279280281282283284"""Tier 4 대응 권고 에이전트두 모드 지원:1. Autonomous (plan=None): LLM이 tool을 자율 호출하는 agent loop2. Conductor (plan 제공): Planner가 지정한 tool 호출 + 단일 LLM synthesis가용 도구: search_knowledge, lookup_incident_history, get_pm_history, check_pm_schedule"""108 unmodified lines필요한 SOP·과거 해결책·PM 윈도우는 도구를 호출해 자율적으로 수집하세요."""CONDUCTOR_SYSTEM_PROMPT = """당신은 반도체 공정 대응 권고 전문가입니다.Central Planner가 이미 필요한 정보(SOP·과거 해결책·PM 윈도우)를 모두 수집해 [수집된 컨텍스트]에 정리해 두었습니다.당신은 추가 도구 호출 없이 그 컨텍스트만 사용해 산출하세요.[최종 산출물]- immediate: 즉시 조치 2~3건 (수 시간 내 실행 가능, meta에 시간·hold 대상·부서 명시)- longterm: 중장기 조치 1~2건- ref_doc_ids: 권고 근거로 실제 사용한 문서 ID (search_knowledge가 반환한 doc_id만)"""def _execute_tier4_plan(plan_tier4: dict, trace_calls: list) -> tuple[str, list[str]]:"""Planner가 지정한 tool들을 직접 호출, 컨텍스트 + 검색 doc_id 리스트 반환"""blocks = []found_docs: list[str] = []for query in plan_tier4.get("search_queries", []):r = dispatch_tool("search_knowledge", {"query": query})trace_calls.append({"name": "search_knowledge", "args": {"query": query}})blocks.append(f"[search_knowledge: {query!r}]\n{r}")try:parsed = json.loads(r)found_docs.extend(h["doc_id"] for h in parsed.get("hits", []))except (json.JSONDecodeError, KeyError):passfor symptom in plan_tier4.get("incident_symptoms", []):r = dispatch_tool("lookup_incident_history", {"symptom": symptom})trace_calls.append({"name": "lookup_incident_history", "args": {"symptom": symptom}})blocks.append(f"[lookup_incident_history: {symptom!r}]\n{r}")for eq_id in plan_tier4.get("equipment_ids", []):r1 = dispatch_tool("get_pm_history", {"equipment_id": eq_id})trace_calls.append({"name": "get_pm_history", "args": {"equipment_id": eq_id}})blocks.append(f"[get_pm_history: {eq_id!r}]\n{r1}")r2 = dispatch_tool("check_pm_schedule", {"equipment_id": eq_id})trace_calls.append({"name": "check_pm_schedule", "args": {"equipment_id": eq_id}})blocks.append(f"[check_pm_schedule: {eq_id!r}]\n{r2}")return "\n\n".join(blocks) if blocks else "(planner가 정보 수집 지시 없음)", found_docsdef _run_response_conductor(alarm: dict, tier1: Tier1, tier2: Tier2, tier3: Tier3,plan: dict, trace: dict | None,) -> Tier4:tool_log: list[dict] = []knowledge, found_docs = _execute_tier4_plan(plan.get("tier4", {}), tool_log)cause_lines = "\n".join(f"- {c['name']} ({c['pct']}%)" for c in tier2["causes"])impact_lots_text = ", ".join(f"{l['label']} {l['lots']}lot/{l['wafers']}장" for l in tier3["impact_lots"])user_prompt = f"""## 이상 알람- 공정: {alarm['title']}, lot: {alarm['lot_id']}## Tier 1: 이상 점수 {tier1['score']}## Tier 2 원인 (기여도 순){cause_lines}## Tier 3 영향- 예상 수율 손실: {tier3['yield_loss']} %p- 영향 WIP: {impact_lots_text}## 수집된 컨텍스트 (Planner 지정){knowledge}위 컨텍스트만 사용해 immediate, longterm, ref_doc_ids를 산출하세요."""resp = client().chat.completions.create(model=SUBAGENT_MODEL,messages=[{"role": "system", "content": CONDUCTOR_SYSTEM_PROMPT},{"role": "user", "content": user_prompt},],response_format={"type": "json_schema","json_schema": {"name": "tier4_part", "schema": LLM_PART_SCHEMA, "strict": True},},)llm_out = json.loads(resp.choices[0].message.content)ref_ids = llm_out.get("ref_doc_ids") or found_docs[:4]refs = [{"id": d, "desc": _doc_description(d)} for d in ref_ids if d]if trace is not None:trace["tool_calls"] = tool_logtrace["iterations"] = 0trace["llm_calls"] = 1trace["mode"] = "conductor"return {"immediate": llm_out["immediate"],"longterm": llm_out["longterm"],"refs": refs,}@traceable(name="Tier4_Response_Agent", run_type="chain")def run_response(alarm: dict, tier1: Tier1, tier2: Tier2, tier3: Tier3,trace: dict | None = None,plan: dict | None = None,) -> Tier4:"""Tier 4 대응 권고. plan 제공 시 conductor 모드(LLM 1회), 아니면 autonomous loop."""if plan is not None:return _run_response_conductor(alarm, tier1, tier2, tier3, plan, trace)# autonomous 모드 (LLM이 tool을 자율 호출하는 기존 loop)messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": _initial_user_prompt(alarm, tier1, tier2, tier3)},50 unmodified linestrace["tool_calls"] = tool_call_logtrace["iterations"] = iterationstrace["llm_calls"] = iterations + 1trace["mode"] = "autonomous"return {"immediate": llm_out["immediate"],
agents/cause.py+90-12
agents/impact.py+102-4
agents/orchestrator.py+127-80
agents/planner.pyAdded+184
agents/response.py+107-4