ドメイン用語集とオントロジーの注入
ドメイン固有の用語と知識をシステムプロンプトに組み込みます。
「ドメイン用語集とオントロジーの注入」はCoddyKit上の無料AI Prompt Engineeringレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Prompt Engineering学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Prompt Engineeringコースには全4レッスンが含まれています。
曖昧性の問題
専門分野の用語には、曖昧なものが数多くあります。「Yield」は金融では債券利回りを意味し、農業では作物の収穫量を意味します。「Resolution」はUIでは画面解像度を意味し、サポートでは問題の解決を意味します。ドメインコンテキストがなければ、モデルは一般言語で最も一般的な意味を選びますが、専門分野ではそれが誤りになることがあります。
用語集の注入パターン
ドメイン用語集をシステムプロンプトに直接注入します。これにより、モデルのデフォルトの語彙を上書きし、セッション全体で専門用語が正しく解釈されるようにできます。
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.')確認問題
債券ポートフォリオを分析するモデルが導入されています。用語集を注入しなかったため、モデルは「この金融商品(instrument)の利回りはどれくらいですか」という質問に対して、作物の収穫量を説明しました。根本原因と解決策は何ですか。
用語集とオントロジー注入のまとめ
ドメイン用語集とオントロジーの注入により、システムレベルで用語の曖昧さを解消できます。
- 用語集の注入:曖昧な用語について、専門分野固有の意味をシステムプロンプトで定義する
- オントロジーの注入:概念階層、関係ルール、分類上の制約を提供する
- 動的な用語集:マスター用語集から関連する用語だけを選び、コンテキストウィンドウを簡潔に保つ
- 複数ドメインの曖昧性解消:コンテキストに基づいてドメインを検出するルールを注入する
- バージョン管理:用語集をバージョン管理し、用語が変更されたらプロンプトを再評価する
- 一貫性チェック:出力を後処理し、用語の意味のずれを検出する
よくある質問
「ドメイン用語集とオントロジーの注入」レッスンは無料ですか?
はい。「ドメイン用語集とオントロジーの注入」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Prompt Engineeringコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Prompt Engineeringコースには全4レッスンが含まれています。
「ドメイン用語集とオントロジーの注入」で何を学びますか?
ドメイン固有の用語と知識をシステムプロンプトに組み込みます。 ブラウザで直接実行するハンズオンコードでAI Prompt Engineeringを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
AI Prompt Engineeringを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのAI Prompt Engineeringは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「ドメイン用語集とオントロジーの注入」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このAI Prompt Engineeringレッスンでコードを書いて実行できますか?
はい。すべてのAI Prompt Engineeringレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- 法律分野のプロンプトパターン
- 医療・臨床プロンプト
- 金融・定量分析プロンプト
- ドメイン用語集とオントロジーの注入