분야 용어집 및 온톨로지 주입
분야별 용어와 지식을 시스템 프롬프트에 삽입합니다.
분야 용어집 및 온톨로지 주입은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Prompt Engineering 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.
구분의 문제
도메인 언어에는 모호한 표현이 많습니다. '수익률'은 금융에서 채권 수익률을, 농업에서 작물 수확량을 의미합니다. '해상도'는 사용자 인터페이스에서 화면 해상도를, 지원 분야에서 문제 해결을 의미합니다. 도메인 맥락이 없으면 모델은 일반 언어에서 가장 흔한 의미를 기본값으로 선택하는데, 전문 분야에서는 이것이 잘못된 의미일 수 있습니다.
용어집 주입 패턴
도메인 용어집을 시스템 프롬프트에 직접 주입하십시오. 이렇게 하면 모델의 기본 어휘를 덮어쓰고 세션 전체에서 도메인별 용어가 올바르게 해석되도록 할 수 있습니다.
FINANCE_GLOSSARY = '''
DOMAIN GLOSSARY (these definitions override general language meaning):
- yield: bond yield (annual return as percentage of bond price), NOT crop or harvest
- duration: interest rate sensitivity measure (modified duration), NOT time length
- spread: yield spread between two bonds, NOT physical spreading
- convexity: second-order price sensitivity to interest rate changes, NOT geometry
- tenor: remaining time to maturity of a financial instrument, NOT musical pitch
- floor: minimum interest rate in a rate agreement, NOT building floor
- cap: maximum interest rate, NOT a hat or market capitalization
- swap: exchange of cash flows between counterparties, NOT physical exchange
- basis: difference between spot and futures price, NOT foundation
'''
FINANCE_SYSTEM_PROMPT = (
'You are a fixed income analyst.\n\n'
+ FINANCE_GLOSSARY +
'\nAlways use these domain definitions when answering questions.'
)
import anthropic
client = anthropic.Anthropic(api_key='YOUR_API_KEY')
response = client.messages.create(
model='claude-opus-4-5', max_tokens=500,
system=FINANCE_SYSTEM_PROMPT,
messages=[{'role': 'user', 'content': 'What is the yield of a 10-year bond?'}]
)
print(response.content[0].text)도메인 용어집 파일 구축
용어집을 구조화된 YAML 파일로 저장하면 버전을 관리하고 여러 프롬프트에서 공유할 수 있으며, 도메인 전문가가 프롬프트 코드를 수정하지 않고도 업데이트할 수 있습니다.
# glossaries/fixed_income.yaml
glossary:
yield:
domain_meaning: Annual return on a bond as a percentage of its current market price
general_meaning: Crop or harvest output
use_domain: true
examples:
- 'The 10-year Treasury yield rose to 4.5%'
- 'Current yield = annual coupon / market price'
duration:
domain_meaning: |
Measure of a bond's price sensitivity to interest rate changes.
Modified duration = -dP/P / dr
general_meaning: Length of time
use_domain: true
basis:
domain_meaning: Difference between spot price and futures price of the same instrument
general_meaning: Foundation or base
use_domain: true
# glossaries/load.py
import yaml
def load_glossary(domain):
with open(f'glossaries/{domain}.yaml') as f:
data = yaml.safe_load(f)
lines = ['DOMAIN GLOSSARY:']
for term, info in data['glossary'].items():
lines.append(f'- {term}: {info["domain_meaning"].strip()}')
return '\n'.join(lines)복잡한 도메인을 위한 온톨로지 주입
온톨로지는 용어집보다 더 포괄적인 개념으로, 개념 간의 관계인 계층 구조, 제약 조건 및 규칙을 정의합니다. 온톨로지를 주입하면 모델이 어떤 개념이 어떤 범주에 속하는지, 그리고 개념들이 서로 어떻게 연결되는지 이해하는 데 도움이 됩니다.
MEDICAL_ONTOLOGY_SNIPPET = '''
CLINICAL ONTOLOGY (use these relationships in all analysis):
Diagnosis Hierarchy:
- Condition > Category > Specific Diagnosis
- "Hypertension" is a specific diagnosis under "Cardiovascular Conditions"
- "Type 2 Diabetes" is under "Endocrine / Metabolic Conditions"
Medication Classes:
- ACE inhibitors (e.g., lisinopril) -> used for: hypertension, heart failure, CKD
- Beta-blockers (e.g., metoprolol) -> used for: hypertension, angina, heart failure
- Statins (e.g., atorvastatin) -> used for: hyperlipidemia, cardiovascular risk
Measurement Rules:
- "BP" means Blood Pressure, format: systolic/diastolic (e.g., 130/85 mmHg)
- "A1c" means glycated hemoglobin; > 6.5% is diagnostic for Type 2 Diabetes
- "eGFR" means estimated Glomerular Filtration Rate; < 60 mL/min/1.73m2 = CKD
Always use ICD-10 categories when classifying diagnoses.
'''
print(MEDICAL_ONTOLOGY_SNIPPET[:300])동적 용어집 생성
대규모 지식 기반에서는 집중형 용어집을 동적으로 생성하십시오. 기준 용어집에서 현재 작업과 가장 관련성이 높은 용어만 추출하여 컨텍스트 창을 간결하게 유지할 수 있습니다.
import json
# master_glossary.json — full domain glossary
MASTER_GLOSSARY = {
'yield': 'Bond yield: annual return as percentage of current market price',
'duration': 'Modified duration: bond price sensitivity to rate changes',
'convexity': 'Second-order rate sensitivity measure',
'swap': 'Exchange of fixed and floating cash flows',
'option': 'Contract giving right (not obligation) to buy/sell an asset',
'beta': 'Stock volatility relative to market index',
'alpha': 'Excess return over benchmark after adjusting for risk',
# ... hundreds more
}
def focused_glossary(user_query, master_glossary, max_terms=10):
'''Select glossary terms most relevant to the user query.'''
query_lower = user_query.lower()
relevant = {}
for term, definition in master_glossary.items():
if term.lower() in query_lower or any(
word in query_lower for word in definition.lower().split()[:5]
):
relevant[term] = definition
if len(relevant) >= max_terms:
break
lines = ['RELEVANT DOMAIN TERMS:']
for t, d in relevant.items():
lines.append(f'- {t}: {d}')
return '\n'.join(lines)
query = 'What is the duration and convexity of this bond portfolio?'
print(focused_glossary(query, MASTER_GLOSSARY))다중 도메인 구분
일부 질의는 여러 도메인에 걸쳐 있습니다. 관련된 모든 도메인의 맥락을 주입하고 대화 맥락에 따라 의미를 구분하도록 모델에 지시하십시오.
MULTI_DOMAIN_SYSTEM = '''
This system serves both agricultural and financial users.
The domain is determined by context cues in the user message.
Domain disambiguation rules:
- If the user mentions "crops", "harvest", "acres", "soil", "planting":
Use AGRICULTURAL definitions: yield = crop output, spread = physical spreading
- If the user mentions "bonds", "portfolio", "maturity", "coupon", "treasuries":
Use FINANCIAL definitions: yield = bond yield, spread = yield spread
- If the domain is ambiguous:
Ask the user to clarify: "Are you asking about agricultural or financial yields?"
AGRICULTURAL GLOSSARY:
- yield: crop output per unit area (e.g., bushels per acre)
- basis: difference between local cash price and futures price for a commodity
FINANCIAL GLOSSARY:
- yield: annual bond return as percentage of current price
- basis: yield spread between two financial instruments
'''
print('Multi-domain system prompt loaded.')
print('The model will ask for clarification when domain is ambiguous.')온톨로지 제약 출력
온톨로지 주입을 사용하면 모델의 출력이 미리 정의된 범주만 사용하도록 제한할 수 있어, 후속 처리를 방해하는 자유 형식의 분류를 방지할 수 있습니다.
SUPPORT_ONTOLOGY_SYSTEM = '''
You are a support ticket classifier for a B2B SaaS company.
TICKET CATEGORY ONTOLOGY (use ONLY these exact category names):
Level 1 Categories:
- Billing > Sub-categories: Invoice Error, Subscription Change, Refund Request, Payment Failure
- Technical > Sub-categories: Bug Report, Performance Issue, Integration Error, Feature Not Working
- Account > Sub-categories: Access Request, User Management, Security Concern, Password Reset
- Feature Request > Sub-categories: New Feature, Enhancement, UI/UX Improvement
CLASSIFICATION RULES:
1. Always return exactly one Level 1 category and one Sub-category.
2. If ticket spans multiple categories, choose the PRIMARY issue.
3. If uncertain, use the category that would route to the most qualified team.
4. Return format: {"category": "Technical", "subcategory": "Bug Report", "confidence": "HIGH"}
Confidence: HIGH (clear), MEDIUM (likely), LOW (ambiguous)
'''
def classify_ticket(ticket_text):
import json
response = client.messages.create(
model='claude-opus-4-5', max_tokens=100,
system=SUPPORT_ONTOLOGY_SYSTEM,
messages=[{'role': 'user', 'content': f'Classify: {ticket_text}'}]
)
return json.loads(response.content[0].text)법률 온톨로지 주입
법률 도메인 온톨로지는 계약 조항의 계층 구조, 당사자 간 관계 및 의무 유형을 정의합니다. 이를 주입하면 모든 계약 분석 작업에서 일관된 분류를 보장할 수 있습니다.
LEGAL_ONTOLOGY = '''
CONTRACT CLAUSE ONTOLOGY:
Obligation Types:
- SHALL: mandatory obligation (enforceable duty)
- MAY: permissive right (optional action)
- SHALL NOT: mandatory prohibition
- WILL: future intention (weaker than SHALL)
Clause Risk Hierarchy:
- CRITICAL: financial exposure > $1M or termination rights
- HIGH: material business impact, IP rights, indemnification
- MEDIUM: operational restrictions, notice requirements
- LOW: administrative provisions, definitions
Party References (standardize to these canonical forms):
- "the Company", "we", "us" -> VENDOR
- "Customer", "Client", "you" -> CUSTOMER
- "third party", "subcontractor" -> THIRD_PARTY
Always use these canonical party names in your analysis.
Do not use the actual company names — replace with canonical form.
'''
print('Legal ontology loaded. Party names will be canonicalized in all analysis.')용어 일관성 검사기
모델의 출력을 받은 후 도메인 용어가 일관되게 사용되고 일반 언어의 의미로 되돌아가지 않는지 확인하십시오. 후처리 검사를 통해 용어 사용의 이탈을 발견할 수 있습니다.
PROHIBITED_GENERAL_MEANINGS = {
# In fixed income context: these general meanings should not appear
'yield': ['harvest', 'crop', 'produce', 'give way', 'surrender'],
'duration': ['how long', 'length of time', 'period of time'],
'floor': ['ground floor', 'building floor', 'floor plan'],
'cap': ['hat', 'market cap', 'bottle cap'],
}
def check_terminology_consistency(text, domain_term):
text_lower = text.lower()
prohibited = PROHIBITED_GENERAL_MEANINGS.get(domain_term, [])
violations = []
for general_phrase in prohibited:
if general_phrase in text_lower:
# Find context window around the violation
idx = text_lower.index(general_phrase)
context = text[max(0, idx-50):idx+80]
violations.append({'phrase': general_phrase, 'context': context})
return violations
# Usage after LLM call
output = 'The yield of the bond is 4.5% per annum based on current market price.'
violations = check_terminology_consistency(output, 'yield')
if violations:
print('Terminology violation detected:', violations)
else:
print('Terminology consistency: PASS')용어집 버전 관리
도메인 용어집은 프롬프트와 함께 버전을 관리해야 합니다. 용어가 변경되면(새로운 규제 정의나 업데이트된 임상 표준 등) 해당 용어를 사용하는 모든 프롬프트를 다시 평가해야 합니다.
# Glossary versioning with impact tracking
GLOSSARY_VERSIONS = {
'1.0.0': {
'yield': 'Bond yield: annual coupon / face value (current yield)',
'duration': 'Macaulay duration'
},
'2.0.0': {
'yield': 'Bond yield: annual return as % of current market price (yield to maturity)',
'duration': 'Modified duration (more precise for risk management)',
'convexity': 'Second-order rate sensitivity (new in v2)' # new term
}
}
def get_affected_prompts(old_version, new_version, prompt_registry):
'''Find prompts that use terms changed between glossary versions.'''
old_terms = set(GLOSSARY_VERSIONS[old_version].keys())
new_terms = set(GLOSSARY_VERSIONS[new_version].keys())
changed_terms = old_terms ^ new_terms # symmetric difference
affected = []
for prompt_id, artifact in prompt_registry.items():
if any(term in artifact['template'] for term in changed_terms):
affected.append(prompt_id)
return affected
print('Prompts affected by glossary v1.0.0 -> v2.0.0 update:', ['rate-analysis-v1', 'bond-report'])부모-자식 관계를 갖는 계층형 온톨로지
완전한 온톨로지는 부모 개념과 자식 개념의 계층 구조를 정의합니다. 계층 구조를 사용해 프롬프트를 작성하면 모델이 지나치게 포괄적이거나 협소하지 않고 적절한 구체성 수준에서 추론할 수 있습니다.
PRODUCT_ONTOLOGY = '''
PRODUCT CATEGORY ONTOLOGY (use for all product classification tasks):
Electronics
Computing
Laptops
Gaming Laptops
Ultrabooks
Workstations
Desktops
Tablets
Consumer Electronics
Smartphones
Smart Speakers
Wearables
Smartwatches
Fitness Trackers
CLASSIFICATION RULES:
1. Always classify to the most specific level where evidence exists.
2. If a product matches multiple branches, use the primary use case.
3. Use exact taxonomy names from above — do not invent new categories.
4. If a product does not fit, use the nearest parent category and
add "[NON-STANDARD: <reason>]" after the category name.
'''
print('Product ontology ready. 4-level hierarchy loaded.')빠른 확인
채권 포트폴리오를 분석하도록 모델을 배포했습니다. 용어집을 주입하지 않으면 모델이 '이 금융 상품의 수익률은 얼마입니까?'라는 질문에 작물 생산량을 설명합니다. 근본 원인과 해결 방법은 무엇입니까?
용어집 및 온톨로지 주입 요약
도메인 용어집과 온톨로지를 주입하면 시스템 수준에서 용어의 모호성을 해결할 수 있습니다:
- 용어집 주입: 모호한 용어의 도메인별 의미를 시스템 프롬프트에 정의합니다
- 온톨로지 주입: 개념 계층 구조, 관계 규칙 및 분류 제약 조건을 제공합니다
- 동적 용어집: 기준 용어집에서 관련 용어만 선택하여 컨텍스트 창을 간결하게 유지합니다
- 다중 도메인 구분: 맥락에 기반한 도메인 감지를 위한 규칙을 주입합니다
- 버전 관리: 용어집의 버전을 관리하고 용어가 변경되면 프롬프트를 다시 평가해야 합니다
- 일관성 검사: 용어 사용의 이탈을 발견하도록 출력을 후처리합니다
자주 묻는 질문
“분야 용어집 및 온톨로지 주입” 강의는 무료인가요?
네 — “분야 용어집 및 온톨로지 주입” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.
“분야 용어집 및 온톨로지 주입”에서 뭘 배우나요?
분야별 용어와 지식을 시스템 프롬프트에 삽입합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Prompt Engineering을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Prompt Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“분야 용어집 및 온톨로지 주입” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Prompt Engineering 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Prompt Engineering 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 법률 분야 프롬프트 패턴
- 의료 및 임상 프롬프트 작성
- 금융 및 정량 분석 프롬프트
- 분야 용어집 및 온톨로지 주입