0Pricing
AI Prompt Engineering · 课时

领域术语表与本体注入

将领域专用术语和知识嵌入系统提示词。

领域术语表与本体注入 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

消歧问题

领域语言充满歧义。“Yield”在金融领域指债券收益率,在农业领域指农作物产量。“Resolution”在用户界面中指屏幕分辨率,在支持服务中指问题解决。没有领域上下文时,模型会默认采用通用语言中最常见的含义——而这在专业领域中往往是错误的。

术语表注入模式

将领域术语表直接注入系统提示词。这会覆盖模型的默认词汇,确保模型在整个会话中正确理解领域专用术语。

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.')

快速检查

某模型被部署用于分析债券投资组合。没有注入术语表时,模型将“这项工具的收益率是多少?”理解为描述农作物产量。根本原因是什么,应如何修复?

术语表与本体注入总结

领域术语表和本体注入可以在系统层面解决术语歧义:

  • 术语表注入:在系统提示词中定义领域专用含义,以处理有歧义的术语
  • 本体注入:提供概念层级、关系规则和分类约束
  • 动态术语表:从主术语表中仅选择相关术语,使上下文窗口保持精简
  • 多领域消歧:注入基于上下文进行领域检测的规则
  • 版本管理:术语表必须进行版本管理,术语发生变化时必须重新评估提示词
  • 一致性检查:对输出进行后处理,以检测术语漂移

常见问题解答

「领域术语表与本体注入」课时是免费的吗?

是的 — 「领域术语表与本体注入」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「领域术语表与本体注入」这节课中我会学到什么?

将领域专用术语和知识嵌入系统提示词。 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「领域术语表与本体注入」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 法律领域的提示词模式
  2. 医学与临床提示词
  3. 金融与定量分析提示词
  4. 领域术语表与本体注入
← 返回 AI Prompt Engineering