hee_!J commited on
Commit ·
d6ae565
1
Parent(s): 149d1d4
feat(tools): agent tool registry - 7개 tool + OpenAI function schema
Browse filesFiles changed (5)
- agents/tools/__init__.pyAdded+69
- agents/tools/equipment.pyAdded+123
- agents/tools/incident.pyAdded+107
- agents/tools/knowledge.pyAdded+48
- agents/tools/process.pyAdded+137
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Agent tool registry - LLM이 자율 호출하는 도구 모음
각 tool은 (function, OpenAI schema) 쌍으로 구성- knowledge.search_knowledge: hybrid RAG 검색- incident.lookup_incident_history: 과거 incident 구조화 조회- equipment.get_pm_history / check_pm_schedule: PM 이력·예정- process.get_downstream_steps / query_wip_status / get_yield_baseline: 공정 의존성·WIP·수율
Tier별 사용 가능 tool 묶음:- TOOLS_CAUSE: Tier 2 원인 분석 (search, incident, pm)- TOOLS_IMPACT: Tier 3 영향 평가 (wip, downstream, yield, pm)- TOOLS_RESPONSE: Tier 4 대응 권고 (search, incident, pm, schedule)
LLM 호출 패턴: from agents.tools import TOOLS_CAUSE, dispatch_tool resp = client().chat.completions.create( model=..., messages=..., tools=TOOLS_CAUSE, tool_choice="auto" ) for tc in resp.choices[0].message.tool_calls or []: result = dispatch_tool(tc.function.name, json.loads(tc.function.arguments))"""import json
from agents.tools import equipment, incident, knowledge, process
_REGISTRY = { "search_knowledge": knowledge.search_knowledge, "lookup_incident_history": incident.lookup_incident_history, "get_pm_history": equipment.get_pm_history, "check_pm_schedule": equipment.check_pm_schedule, "get_downstream_steps": process.get_downstream_steps, "query_wip_status": process.query_wip_status, "get_yield_baseline": process.get_yield_baseline,}
# Tier별 노출 tool 묶음TOOLS_CAUSE = [ knowledge.SCHEMA, incident.SCHEMA, equipment.SCHEMA_GET_PM,]TOOLS_IMPACT = [ process.SCHEMA_WIP, process.SCHEMA_DOWNSTREAM, process.SCHEMA_YIELD, equipment.SCHEMA_GET_PM,]TOOLS_RESPONSE = [ knowledge.SCHEMA, incident.SCHEMA, equipment.SCHEMA_GET_PM, equipment.SCHEMA_CHECK_PM,]
def dispatch_tool(name: str, args: dict) -> str: """tool 함수를 이름으로 호출, 결과를 JSON string으로 반환 (LLM 입력용)""" fn = _REGISTRY.get(name) if fn is None: return json.dumps({"error": f"unknown tool: {name}"}, ensure_ascii=False) try: result = fn(**args) except TypeError as e: return json.dumps({"error": f"invalid args: {e}"}, ensure_ascii=False) return json.dumps(result, ensure_ascii=False, default=str)
def all_tool_names() -> list[str]: return list(_REGISTRY.keys())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""장비 관련 tools - PM 이력 조회 + 가용 윈도우
실 fab에선 EAP(Equipment Automation Program) / CIM 시스템에서 조회되는 값오늘 기준일은 2026-05-18 (데모 고정)"""from datetime import date
TODAY = date(2026, 5, 18)
# 알람 ID -> 대표 장비 매핑ALARM_EQUIPMENT = { "A1": "ASML-PH-01", "A2": "TEL-ET-03", "A3": "AMAT-CMP-02",}
_EQUIPMENT = { "ASML-PH-01": { "kind": "Photo Scanner (lens, stage)", "process": "Photo", "last_pm": date(2026, 5, 4), "pm_cycle_days": 21, "next_pm_windows": ["2026-05-19 02:00~06:00", "2026-05-21 22:00~02:00"], }, "TEL-ET-03": { "kind": "Etch Chamber", "process": "Etch", "last_pm": date(2026, 5, 11), "pm_cycle_days": 30, "next_pm_windows": ["2026-05-24 03:00~07:00"], }, "AMAT-CMP-02": { "kind": "CMP Polisher (slurry, pad)", "process": "CMP", "last_pm": date(2026, 4, 27), "pm_cycle_days": 21, "next_pm_windows": ["2026-05-19 04:00~07:00", "2026-05-20 23:00~03:00"], }, "ASM-DIF-04": { "kind": "Diffusion Furnace", "process": "Diffusion", "last_pm": date(2026, 4, 30), "pm_cycle_days": 60, "next_pm_windows": ["2026-05-25 06:00~10:00"], },}
def get_pm_history(equipment_id: str) -> dict: """장비 마지막 PM 이력 + 경과일 + 다음 PM 예정일 반환
overdue: 다음 PM 예정일을 지났는가 """ eq = _EQUIPMENT.get(equipment_id) if not eq: return {"error": f"등록되지 않은 장비: {equipment_id}"} days_since = (TODAY - eq["last_pm"]).days overdue = days_since > eq["pm_cycle_days"] return { "equipment_id": equipment_id, "kind": eq["kind"], "process": eq["process"], "last_pm_date": eq["last_pm"].isoformat(), "days_since_pm": days_since, "pm_cycle_days": eq["pm_cycle_days"], "overdue": overdue, "overdue_days": max(0, days_since - eq["pm_cycle_days"]), }
def check_pm_schedule(equipment_id: str) -> dict: """다음 7일 내 사용 가능한 PM 정비 윈도우 목록 반환""" eq = _EQUIPMENT.get(equipment_id) if not eq: return {"error": f"등록되지 않은 장비: {equipment_id}"} return { "equipment_id": equipment_id, "available_windows": eq["next_pm_windows"], }
SCHEMA_GET_PM = { "type": "function", "function": { "name": "get_pm_history", "description": ( "장비의 마지막 PM(예방정비) 이력과 경과일, overdue 여부를 조회합니다. " "원인 분석에서 'PM 누락이 원인인가' 판단할 때 활용하세요. " "장비 ID는 알람별로 ASML-PH-01(A1), TEL-ET-03(A2), AMAT-CMP-02(A3) 가 매핑됩니다." ), "parameters": { "type": "object", "properties": { "equipment_id": { "type": "string", "description": "장비 ID (예: 'ASML-PH-01')", }, }, "required": ["equipment_id"], }, },}
SCHEMA_CHECK_PM = { "type": "function", "function": { "name": "check_pm_schedule", "description": ( "다음 7일 내 PM 정비 가능 윈도우를 조회합니다. " "대응 권고에서 '언제 PM을 투입할 수 있는가'를 답할 때 사용하세요." ), "parameters": { "type": "object", "properties": { "equipment_id": { "type": "string", "description": "장비 ID", }, }, "required": ["equipment_id"], }, },}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107"""lookup_incident_history tool - 과거 incident 구조화 조회
knowledge/INC-*.md 의 RAG 검색과 별도로, 증상 키워드로 구조화 incident 레코드를 반환(MES/incident DB 모방, 실 fab에선 Maximo/Splunk 등에서 조회)"""
_INCIDENTS = [ { "id": "INC-2024-0312", "date": "2024-03-12", "process": "Photo", "symptom": "CD-X 산포 증가", "root_cause": "렌즈 오염", "resolution": "긴급 PM 후 정상화 (2h 소요)", "yield_recovery": "3.1% → 0.4%", "keywords": ["cd", "산포", "렌즈", "오염", "photo", "노광"], }, { "id": "INC-2024-0289", "date": "2024-02-28", "process": "Photo", "symptom": "스테이지 진동 이상치", "root_cause": "스테이지 베어링 마모", "resolution": "베어링 교체 후 alignment 재수행 (6h)", "yield_recovery": "1.8% → 0.2%", "keywords": ["스테이지", "진동", "베어링", "alignment", "photo"], }, { "id": "INC-CMP-2025-0142", "date": "2025-08-14", "process": "CMP", "symptom": "MRR(재료 제거율) 산포 증가", "root_cause": "슬러리 유량 변동", "resolution": "슬러리 펌프 교체 + 유량 센서 재교정 (4h)", "yield_recovery": "2.4% → 0.3%", "keywords": ["mrr", "슬러리", "유량", "cmp", "재료", "제거율"], }, { "id": "INC-ET-2024-0301", "date": "2024-03-01", "process": "Etch", "symptom": "트렌치 깊이 부족", "root_cause": "식각 가스 유량 저하", "resolution": "가스 라인 청소 + MFC 교정 (3h)", "yield_recovery": "2.0% → 0.5%", "keywords": ["트렌치", "깊이", "식각", "가스", "mfc", "etch"], }, { "id": "INC-2023-0892", "date": "2023-11-22", "process": "Photo", "symptom": "Focus 편차 증가", "root_cause": "스테이지 평탄도 이상", "resolution": "스테이지 leveling 재수행 (2h)", "yield_recovery": "1.5% → 0.3%", "keywords": ["focus", "편차", "평탄도", "leveling", "photo"], },]
def lookup_incident_history(symptom: str, max_results: int = 3) -> dict: """증상 키워드로 과거 incident DB 조회, 일치 키워드 수로 랭킹
반환: {"incidents": [{"id", "date", "process", "symptom", "root_cause", "resolution", "yield_recovery"}, ...]} """ q = symptom.lower() q_tokens = [t for t in q.replace(",", " ").split() if len(t) >= 2] scored = [] for inc in _INCIDENTS: score = sum(1 for kw in inc["keywords"] if any(kw in t or t in kw for t in q_tokens)) if score > 0: scored.append((score, inc)) scored.sort(key=lambda x: -x[0]) matched = [ {k: v for k, v in inc.items() if k != "keywords"} for _, inc in scored[:max_results] ] return {"incidents": matched}
SCHEMA = { "type": "function", "function": { "name": "lookup_incident_history", "description": ( "과거 incident DB에서 증상 키워드와 일치하는 사례를 조회합니다. " "구조화된 레코드(원인, 해결책, 소요시간, yield 회복률)를 반환하므로 " "유사 사례 기반 의사결정에 활용하세요." ), "parameters": { "type": "object", "properties": { "symptom": { "type": "string", "description": "증상 키워드 (예: 'CD 산포 증가', '슬러리 유량 이상')", }, "max_results": { "type": "integer", "description": "최대 반환 건수 (기본 3)", "default": 3, }, }, "required": ["symptom"], }, },}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""search_knowledge tool - RAG 검색을 LLM이 자율 호출
기존 agents.rag.store.search()를 tool 인터페이스로 노출LLM이 추가 정보가 필요하다고 판단할 때 호출"""from agents.rag.store import load_document, search
def search_knowledge(query: str, top_k: int = 3) -> dict: """사내 지식 문서(INC/FMEA/SOP/FLOW)를 의미 + 키워드 hybrid 검색
반환: {"hits": [{"doc_id": ..., "snippet": 첫 400자}, ...]} """ doc_ids = search(query, top_k=top_k) hits = [] for doc_id in doc_ids: text = load_document(doc_id) snippet = text[:400] + ("..." if len(text) > 400 else "") hits.append({"doc_id": doc_id, "snippet": snippet}) return {"hits": hits}
SCHEMA = { "type": "function", "function": { "name": "search_knowledge", "description": ( "사내 지식 문서(과거 사례 INC, 실패 모드 FMEA, 표준 절차 SOP, 공정 흐름 FLOW)를 " "hybrid 검색해 관련 문서의 doc_id와 본문 요약을 반환합니다. " "원인 분석·대응 권고에 필요한 도메인 컨텍스트를 가져올 때 사용하세요." ), "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "검색할 키워드/질의문 (예: 'CMP 슬러리 유량 이상')", }, "top_k": { "type": "integer", "description": "반환할 문서 수 (기본 3)", "default": 3, }, }, "required": ["query"], }, },}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""공정 관련 tools - downstream 의존성 + WIP + yield baseline
실 fab에선 MES + Yield Management System에서 조회되는 값"""from data.wip import get_affected_wip
# 공정 흐름 (대표 라인: Photo -> Etch -> CMP -> Diffusion -> Implant -> Metal -> Test)# 각 entry는 (downstream_stage, typical_delta_pct, severity)_DOWNSTREAM = { "Photo": [ ("Etch", 18, "impacted"), ("CMP", 5, "minor"), ], "Etch": [ ("CMP", 15, "impacted"), ("Diffusion", 3, "minor"), ], "CMP": [ ("Diffusion", 8, "impacted"), ("Implant", 12, "impacted"), ("Test", 6, "minor"), ], "Diffusion": [ ("Implant", 10, "impacted"), ("Metal", 4, "minor"), ], "Implant": [ ("Metal", 7, "impacted"), ("Test", 5, "minor"), ],}
# 공정별 yield 기준선 (최근 30일 평균, %)_YIELD_BASELINE = { "Photo": 96.4, "Etch": 95.8, "CMP": 96.1, "Diffusion": 97.2, "Implant": 96.7,}
def get_downstream_steps(current_stage: str) -> dict: """현재 공정 이후로 영향 받는 후공정 목록 반환
각 후공정에 대해 typical delta(%, 영향 강도)와 severity(impacted/minor) 제공 """ deps = _DOWNSTREAM.get(current_stage, []) return { "current_stage": current_stage, "downstream": [ {"stage": s, "typical_delta_pct": d, "severity": sev} for s, d, sev in deps ], }
def query_wip_status(alarm_id: str) -> dict: """알람으로 영향 받는 WIP(가공중·대기중) lot 수 + wafer 수 조회""" lots = get_affected_wip(alarm_id) return {"alarm_id": alarm_id, "wip": lots}
def get_yield_baseline(process: str) -> dict: """공정의 최근 30일 yield 기준선(%) 반환
이상 발생 시 baseline 대비 yield_loss 계산에 사용 """ baseline = _YIELD_BASELINE.get(process) if baseline is None: return {"error": f"등록되지 않은 공정: {process}"} return {"process": process, "baseline_yield_pct": baseline, "window": "최근 30일"}
SCHEMA_DOWNSTREAM = { "type": "function", "function": { "name": "get_downstream_steps", "description": ( "현재 공정 이후 영향 받는 후공정 목록을 반환합니다. " "각 후공정의 일반적 영향 강도(typical_delta_pct)와 severity(impacted/minor)를 포함. " "Tier 3 영향 평가에서 downstream_dependencies 산출에 사용하세요." ), "parameters": { "type": "object", "properties": { "current_stage": { "type": "string", "description": "현재 공정 (Photo, Etch, CMP, Diffusion, Implant 중)", }, }, "required": ["current_stage"], }, },}
SCHEMA_WIP = { "type": "function", "function": { "name": "query_wip_status", "description": ( "알람으로 영향 받는 WIP(가공중·대기중) lot/wafer 수를 MES에서 조회합니다. " "Tier 3 impact_lots 필드를 채울 때 사용하세요." ), "parameters": { "type": "object", "properties": { "alarm_id": { "type": "string", "description": "알람 ID (A1, A2, A3)", }, }, "required": ["alarm_id"], }, },}
SCHEMA_YIELD = { "type": "function", "function": { "name": "get_yield_baseline", "description": ( "공정의 최근 30일 yield 기준선(%)을 조회합니다. " "yield_loss를 baseline 대비로 정량화할 때 사용하세요." ), "parameters": { "type": "object", "properties": { "process": { "type": "string", "description": "공정 이름 (Photo, Etch, CMP, Diffusion, Implant)", }, }, "required": ["process"], }, },}agents/tools/__init__.pyAdded+69
agents/tools/equipment.pyAdded+123
agents/tools/incident.pyAdded+107
agents/tools/knowledge.pyAdded+48
agents/tools/process.pyAdded+137