摘要

给LLM喂信息就像给文档加目录和标点——分隔符和标记系统让你的上下文”井井有条”,模型能更准确地找到、理解和利用信息。这篇文章手把手教你设计一套好用的标记系统,不管是自己用还是团队协作都够用。

先搞清楚:为什么要用分隔符和标记?

想象一下这两个场景

场景A(没有标记):

今天天气真好,我们去公园吧。公园里有很多花。
红色的玫瑰开了。蓝色的薰衣草也开了。
小张和小李一起去。他们带了野餐垫。
然后他们去划船了。船很稳。小张会游泳。
小李不会。等等,我刚才说到哪了?

场景B(有标记):

[地点] 公园
[活动] 野餐、赏花、划船

[人物]
- 小张:会游泳
- 小李:不会游泳

[时间] 今天上午

[发生了什么]
1. 到达公园
2. 赏花(玫瑰、薰衣草)
3. 野餐
4. 划船

场景B的信息组织方式,LLM能更快理解、更好利用。

分隔符和标记的本质作用

  1. 边界清晰:告诉模型”这是一段完整的意思”
  2. 层次分明:让模型知道”哪个是标题,哪个是内容”
  3. 重要性区分:让模型知道”这部分更重要”
  4. 来源可追溯:让模型知道”这个信息从哪来的”

一、分隔符基础:给内容分块

什么是分隔符?

分隔符就是用来划分内容边界的符号或标记。就像文章里的”第一段”、“第二段”之间的空行,或者是书里的”章节标题”。

分隔符的常见类型

类型示例什么时候用
---三个横杠通用分隔,简洁明了
***三个星号分隔大段落
─────Unicode横线视觉上更明显
## 标题Markdown标题章节划分
<section>XML标签需要精确语义时

实战:各种分隔符写法

1. 简单横杠分隔

这是第一段内容...
 
---
 
这是第二段内容...
 
---
 
这是第三段内容...

2. 带标题的分隔

═══════════════════════════════════════════════════
[第一部分:项目背景]
═══════════════════════════════════════════════════
 
这部分包含背景信息...
 
═══════════════════════════════════════════════════
[第二部分:核心功能]
═══════════════════════════════════════════════════
 
这部分是核心功能说明...

3. 卡片式分隔

┌─────────────────────────────────────────┐
│ 📋 用户故事 #001                          │
│ 作为产品经理,我希望看到用户数据...         │
└─────────────────────────────────────────┘
 
┌─────────────────────────────────────────┐
│ 📋 用户故事 #002                          │
│ 作为运营人员,我希望导出报表...            │
└─────────────────────────────────────────┘

4. 代码实现:自动生成分隔符

class SectionDelimiters:
    """Section分隔符生成器"""
    
    # 预定义样式
    DELIMITER_STYLES = {
        'heavy': {
            'line': '═' * 50,
            'wrapper': lambda title: f"{'═' * 50}\n{title}\n{'═' * 50}"
        },
        'light': {
            'line': '─' * 50,
            'wrapper': lambda title: f"{'─' * 50}\n{title}\n{'─' * 50}"
        },
        'markdown': {
            'line': None,
            'wrapper': lambda title: f"## {title}"
        },
        'box': {
            'line': '─' * 50,
            'top': '┌' + '─' * 48 + '┐',
            'bottom': '└' + '─' * 48 + '┘',
            'wrapper': lambda title: f"┌{'─' * 48}\n{title:^46}\n{'─' * 48}┘"
        }
    }
    
    @classmethod
    def create_section(cls, title: str, style: str = 'heavy') -> str:
        """创建带分隔符的section"""
        config = cls.DELIMITER_STYLES.get(style, cls.DELIMITER_STYLES['heavy'])
        return config['wrapper'](title)
    
    @classmethod
    def create_document(cls, sections: list, style: str = 'heavy') -> str:
        """生成完整文档"""
        result = []
        for i, section in enumerate(sections, 1):
            title = section.get('title', f'第{i}节')
            content = section.get('content', '')
            
            result.append(cls.create_section(title, style))
            result.append('')
            result.append(content)
            result.append('')
        
        return '\n'.join(result)
 
# 使用示例
doc = SectionDelimiters.create_document([
    {
        'title': '[📚 背景介绍]',
        'content': '这是背景信息...'
    },
    {
        'title': '[🎯 核心目标]',
        'content': '这是核心目标...'
    }
], style='heavy')
 
print(doc)

二、标记系统:给信息打标签

什么是标记?

标记就是给信息贴上语义标签,告诉模型”这段内容是什么类型”。

常见标记类型

[来源标注] 📄 《人工智能导论》, 第3章, 作者: 张华, 2024年
 
[质量标记] 🟢 高可信度 - 官方来源
          🟡 中等可信度 - 一般来源
          🔴 低可信度 - 需谨慎使用
 
[优先级]   🔴 P0 - 紧急
          🟠 P1 - 高
          🟡 P2 - 中
          🟢 P3 - 低
 
[时间戳]   ⏰ 实时 - 刚刚更新
          📅 近期 - 30天内
          📆 中期 - 6个月内
          📜 历史 - 超过6个月

语义化的Section设计

# 语义化的Section模板
SECTION_TEMPLATES = {
    'instruction': {
        'start': '[📋 任务说明]',
        'emoji': '📋',
        'priority': 'high'
    },
    'context': {
        'start': '[📚 背景信息]',
        'emoji': '📚',
        'priority': 'medium'
    },
    'example': {
        'start': '[💡 示例]',
        'emoji': '💡',
        'priority': 'medium'
    },
    'warning': {
        'start': '[⚠️ 注意]',
        'emoji': '⚠️',
        'priority': 'high'
    },
    'reference': {
        'start': '[📖 参考资料]',
        'emoji': '📖',
        'priority': 'low'
    }
}
 
def build_semantic_context(sections: list) -> str:
    """
    构建语义化的上下文
    
    按优先级排序,确保重要的先被看到
    """
    # 定义优先级
    priority_order = {'high': 0, 'medium': 1, 'low': 2}
    
    # 按优先级排序
    def get_priority(section):
        template = SECTION_TEMPLATES.get(section['type'], SECTION_TEMPLATES['context'])
        return priority_order.get(template['priority'], 1)
    
    sorted_sections = sorted(sections, key=get_priority)
    
    # 构建输出
    result = []
    for section in sorted_sections:
        template = SECTION_TEMPLATES.get(section['type'], SECTION_TEMPLATES['context'])
        result.append(template['start'])
        result.append(section['content'])
        result.append('')  # 空行分隔
    
    return '\n'.join(result)
 
# 使用示例
context = build_semantic_context([
    {'type': 'warning', 'content': '不要使用已废弃的API!'},
    {'type': 'context', 'content': '系统运行在Python 3.9环境'},
    {'type': 'instruction', 'content': '请实现用户登录功能'},
    {'type': 'example', 'content': '示例代码...'},
])

三、Item分隔:列表和卡片

简单列表分隔

## 可用功能
 
---
 
[1️⃣] **用户管理**
  - 创建用户
  - 编辑用户
  - 删除用户
 
---
 
[2️⃣] **权限控制**
  - 分配角色
  - 设置权限
  - 审计日志
 
---
 
[3️⃣] **系统配置**
  - 基本设置
  - 通知配置
  - 安全设置

卡片式Item

┌─────────────────────────────────────────────────┐
│ 📦 项目A                                          │
│ ────────────────────────────────────────────────│
│ • 状态: 进行中 🔄                                  │
│ • 负责人: 张三                                    │
│ • 进度: 65% ████████████░░░░░░░░              │
│ • 截止: 2024-06-15                              │
└─────────────────────────────────────────────────┘
 
┌─────────────────────────────────────────────────┐
│ 📦 项目B                                          │
│ ────────────────────────────────────────────────│
│ • 状态: 已完成 ✅                                 │
│ • 负责人: 李四                                    │
│ • 进度: 100% ████████████████████████████      │
│ • 截止: 2024-05-01                              │
└─────────────────────────────────────────────────┘

代码实现:生成卡片

class CardBuilder:
    """卡片生成器"""
    
    @staticmethod
    def create_card(
        title: str,
        items: dict,
        width: int = 50,
        emoji: str = '📋'
    ) -> str:
        """创建单个卡片"""
        
        # 上边框
        top = '┌' + '─' * (width - 2) + '┐'
        
        # 标题行
        title_line = f'│ {emoji} {title:<{width - 4}} │'
        
        # 分隔线
        divider = '│' + '─' * (width - 2) + '│'
        
        # 内容行
        content_lines = []
        for key, value in items.items():
            line = f'│ • {key}: {value:<{width - 9}} │'
            if len(line) > width:
                # 如果太长,分行
                line = f'│ • {key}: │'
                content_lines.append(line)
                # 折行
                wrapped = f'│   {value:<{width - 6}} │'
                content_lines.append(wrapped)
            else:
                content_lines.append(line)
        
        # 下边框
        bottom = '└' + '─' * (width - 2) + '┘'
        
        # 组合
        card_lines = [top, title_line, divider] + content_lines + [bottom]
        
        return '\n'.join(card_lines)
    
    @staticmethod
    def create_card_grid(cards: list, width: int = 50) -> str:
        """创建卡片网格"""
        result = []
        for i, card in enumerate(cards):
            result.append(CardBuilder.create_card(
                title=card.get('title', f'项目{i+1}'),
                items=card.get('items', {}),
                width=width,
                emoji=card.get('emoji', '📋')
            ))
            result.append('')  # 卡片间距
        
        return '\n'.join(result)
 
# 使用示例
card = CardBuilder.create_card(
    title="用户登录功能",
    items={
        "优先级": "P1 🟠",
        "负责人": "小王",
        "状态": "进行中 🔄",
        "预计工时": "3天"
    }
)
print(card)

四、来源标注:让信息可溯源

来源标记的必要性

LLM有时候会”编造”信息,如果你的上下文里标注了来源,模型会更有依据地回答,也能让用户知道答案的出处。

来源标记的写法

# 直接引用
> 来源: 《人工智能导论》, 第3章, 作者: 张华, 2024年
 
# 数据来源
[数据1] 来自: 国家统计局2024年度报告
[数据2] 来自: OpenAI官方文档
[数据3] 来自: 公司内部数据库 (最后更新: 2024-01-15)
 
# 参考文档
📄 参考: 政策文件-2024-001号
📄 参考: 技术规范-v2.3
📄 参考: API文档 https://api.example.com/docs

代码实现:来源追踪系统

from dataclasses import dataclass
from enum import Enum
from typing import Optional, List
from datetime import datetime
 
class SourceType(Enum):
    """信息来源类型"""
    DOCUMENT = "document"
    WEB_PAGE = "web_page"
    DATABASE = "database"
    API = "api"
    BOOK = "book"
    PAPER = "paper"
    INTERNAL = "internal"
 
@dataclass
class Source:
    """信息来源"""
    source_type: SourceType
    identifier: str
    title: str
    author: Optional[str] = None
    url: Optional[str] = None
    date: Optional[str] = None
    reliability: float = 1.0  # 0-1可信度
    
    def to_tag(self) -> str:
        """转换为标注字符串"""
        icon_map = {
            SourceType.DOCUMENT: "📄",
            SourceType.WEB_PAGE: "🌐",
            SourceType.DATABASE: "💾",
            SourceType.API: "🔌",
            SourceType.BOOK: "📚",
            SourceType.PAPER: "📝",
            SourceType.INTERNAL: "🏢"
        }
        
        icon = icon_map.get(self.source_type, "📌")
        parts = [f"{icon} [{self.source_type.value}]", self.title]
        
        if self.author:
            parts.append(f"作者: {self.author}")
        if self.date:
            parts.append(f"日期: {self.date}")
        
        # 可信度指示
        if self.reliability >= 0.8:
            parts.append("🟢")
        elif self.reliability >= 0.5:
            parts.append("🟡")
        else:
            parts.append("🔴")
        
        return " | ".join(parts)
 
class SourceTracker:
    """来源追踪器"""
    
    def __init__(self):
        self.sources: List[Source] = []
        self.citation_format = "[{num}]"
    
    def add_source(self, source: Source) -> str:
        """添加来源并返回引用标记"""
        # 检查是否已存在
        for i, s in enumerate(self.sources):
            if s.identifier == source.identifier:
                return self.citation_format.format(num=i + 1)
        
        self.sources.append(source)
        return self.citation_format.format(num=len(self.sources))
    
    def format_context_with_sources(
        self,
        content: str,
        citations: dict
    ) -> str:
        """在上下文中插入来源标注"""
        # 简化实现
        result = content
        
        for position, source_num in citations.items():
            citation_tag = self.citation_format.format(num=source_num)
            # 在对应位置插入引用
            # 这里简化处理
            result += f"\n{citation_tag}"
        
        return result
    
    def generate_reference_section(self) -> str:
        """生成参考资源部分"""
        if not self.sources:
            return ""
        
        lines = ["\n## 参考资源\n"]
        
        for i, source in enumerate(self.sources, 1):
            lines.append(f"{self.citation_format.format(num=i)} {source.to_tag()}")
        
        return '\n'.join(lines)
 
# 使用示例
tracker = SourceTracker()
 
# 添加来源
s1 = tracker.add_source(Source(
    source_type=SourceType.BOOK,
    identifier="ai-intro-2024",
    title="人工智能导论",
    author="张华",
    date="2024",
    reliability=0.9
))
 
s2 = tracker.add_source(Source(
    source_type=SourceType.WEB_PAGE,
    identifier="openai-docs",
    title="OpenAI API文档",
    url="https://docs.openai.com",
    date="2024-01",
    reliability=0.95
))
 
# 使用
context = f"""
根据{s1}的研究,人工智能的发展经历了三个阶段。
OpenAI的{s2}提供了详细的API使用指南。
"""
 
print(context)
print(tracker.generate_reference_section())

五、质量标记:告诉模型哪些更可信

可靠性等级

## 内容质量标记
 
### 可靠性等级
 
🟢 **高可信度** - 官方来源、经过验证的信息
  - 官方文档
  - 学术论文
  - 权威机构发布
 
🟡 **中等可信度** - 一般来源、可能存在误差
  - 新闻报道
  - 行业分析
  - 用户反馈
 
🔴 **低可信度** - 需谨慎使用、可能不准确
  - 社交媒体
  - 匿名来源
  - 未经证实
 
### 信息时效性
 
**实时** - 刚刚更新的信息
📅 **近期** - 30天内更新
📆 **中期** - 6个月内更新
📜 **历史** - 超过6个月

代码实现:质量标记器

class QualityMarker:
    """质量标记器"""
    
    RELIABILITY_LEVELS = {
        'high': {'icon': '🟢', 'label': '高可信度', 'score': 1.0},
        'medium': {'icon': '🟡', 'label': '中等可信度', 'score': 0.6},
        'low': {'icon': '🔴', 'label': '低可信度', 'score': 0.3},
        'unknown': {'icon': '⚪', 'label': '可信度未知', 'score': 0.5}
    }
    
    TIMELINESS_LEVELS = {
        'realtime': {'icon': '⏰', 'label': '实时', 'days': 0},
        'recent': {'icon': '📅', 'label': '近期', 'days': 30},
        'medium': {'icon': '📆', 'label': '中期', 'days': 180},
        'historical': {'icon': '📜', 'label': '历史', 'days': 10000}
    }
    
    @classmethod
    def mark_content(
        cls,
        content: str,
        reliability: str = 'unknown',
        timeliness: str = 'recent',
        custom_notes: str = None
    ) -> str:
        """为内容添加质量标记"""
        rel_info = cls.RELIABILITY_LEVELS.get(
            reliability, 
            cls.RELIABILITY_LEVELS['unknown']
        )
        time_info = cls.TIMELINESS_LEVELS.get(
            timeliness, 
            cls.TIMELINESS_LEVELS['recent']
        )
        
        header = f"{rel_info['icon']} {rel_info['label']} | {time_info['icon']} {time_info['label']}"
        if custom_notes:
            header += f" | 📝 {custom_notes}"
        
        return f"> {header}\n>\n> {content}"
    
    @classmethod
    def filter_by_quality(
        cls,
        contents: list,
        min_reliability: str = 'unknown',
        max_age_days: int = None
    ) -> list:
        """按质量过滤内容"""
        min_score = cls.RELIABILITY_LEVELS[min_reliability]['score']
        
        filtered = []
        for content in contents:
            reliability_score = cls.RELIABILITY_LEVELS.get(
                content.get('reliability', 'unknown'), {}
            ).get('score', 0.5)
            
            if reliability_score < min_score:
                continue
            
            if max_age_days and content.get('age_days', 0) > max_age_days:
                continue
            
            filtered.append(content)
        
        return filtered
 
# 使用示例
marked = QualityMarker.mark_content(
    "根据最新研究,LLM的上下文窗口正在快速扩大...",
    reliability='high',
    timeliness='recent',
    custom_notes='来源: Nature AI"
)
print(marked)

六、优先级标记:告诉模型什么更紧急

优先级系统

## 用户问题处理流程
 
🔴 **[P0 - 紧急]** 系统宕机、数据丢失风险
   → 需要立即响应,5分钟内处理
 
🟠 **[P1 - 高]** 核心功能不可用
   → 24小时内处理
 
🟡 **[P2 - 中]** 功能异常、部分受影响
   → 1周内处理
 
🟢 **[P3 - 低]** 体验优化、非功能性问题
   → 按计划处理

代码实现:优先级标记器

from enum import IntEnum
 
class Priority(IntEnum):
    P0_CRITICAL = 0  # 紧急
    P1_HIGH = 1       # 高
    P2_MEDIUM = 2     # 中
    P3_LOW = 3        # 低
 
class PriorityMarker:
    """优先级标记器"""
    
    PRIORITY_CONFIG = {
        Priority.P0_CRITICAL: {
            'icon': '🔴',
            'label': 'P0-紧急',
            'response_time': '5分钟',
            'sla': '立即处理'
        },
        Priority.P1_HIGH: {
            'icon': '🟠',
            'label': 'P1-高',
            'response_time': '24小时',
            'sla': '尽快处理'
        },
        Priority.P2_MEDIUM: {
            'icon': '🟡',
            'label': 'P2-中',
            'response_time': '1周',
            'sla': '按计划处理'
        },
        Priority.P3_LOW: {
            'icon': '🟢',
            'label': 'P3-低',
            'response_time': '待定',
            'sla': '可选处理'
        }
    }
    
    @classmethod
    def mark_task(cls, task: dict, priority: Priority) -> str:
        """标记任务优先级"""
        config = cls.PRIORITY_CONFIG[priority]
        
        return f"""{config['icon']} **[{config['label']}]** {task.get('title', 'Untitled')}
- 描述: {task.get('description', '')}
- 响应时间: {config['response_time']}
- SLA: {config['sla']}"""
    
    @classmethod
    def mark_task_list(cls, tasks: list) -> str:
        """标记任务列表(按优先级排序)"""
        # 按优先级排序
        sorted_tasks = sorted(
            tasks,
            key=lambda x: x.get('priority', Priority.P3_LOW)
        )
        
        result = ["## 待处理任务\n"]
        for i, task in enumerate(sorted_tasks, 1):
            priority = task.get('priority', Priority.P3_LOW)
            marked = cls.mark_task(task, priority)
            result.append(f"{i}. {marked}")
            result.append("")
        
        return '\n'.join(result)
 
# 使用示例
tasks = [
    {'title': '修复登录Bug', 'description': '用户无法登录', 'priority': Priority.P0_CRITICAL},
    {'title': '优化加载速度', 'description': '页面加载太慢', 'priority': Priority.P2_MEDIUM},
    {'title': '添加深色模式', 'description': '用户请求深色模式', 'priority': Priority.P3_LOW},
]
 
print(PriorityMarker.mark_task_list(tasks))

七、与注意力机制的配合

为什么标记能提升效果?

LLM的注意力机制会”关注”上下文的不同部分。合理的标记可以:

  1. 强化重要内容:通过重复标记吸引注意
  2. 建立关联:一致的标记建立跨内容关系
  3. 引导检索:通过标记帮助定位关键信息

注意力增强技术

class AttentionEnhancer:
    """注意力增强器"""
    
    @staticmethod
    def structure_for_attention(content: str, structure: str = "pyramid") -> str:
        """
        按注意力模型组织内容
        
        structure: 
        - 'pyramid': 最重要在前(摘要-细节)
        - 'inverted': 最重要在后(细节-结论)
        """
        lines = content.split('\n')
        
        if structure == "pyramid":
            # 摘要/结论放前面
            conclusion = [l for l in lines if any(kw in l for kw in ['结论', '总结', '建议', '核心'])]
            detail = [l for l in lines if l not in conclusion]
            return '\n'.join(conclusion + detail)
        
        elif structure == "inverted":
            # 细节在前,结论在后
            summary = [l for l in lines if any(kw in l for kw in ['结论', '总结'])]
            detail = [l for l in lines if l not in summary]
            return '\n'.join(detail + summary)
        
        return content
 
class PositionOptimizer:
    """位置优化器 - 解决Lost in Middle问题"""
    
    @staticmethod
    def reorder_for_llm(items: list, query: str) -> list:
        """
        重排项目以优化LLM注意力
        
        策略:最重要的放开头和结尾,中间的可以适当牺牲
        """
        if len(items) <= 3:
            return items
        
        # 计算每个项目与查询的相关性(简化)
        scored = []
        for item in items:
            score = sum(1 for kw in item.get('keywords', []) if kw in query)
            scored.append((score, item))
        
        scored.sort(key=lambda x: x[0], reverse=True)
        
        # 重排:最高相关性放开头,次高放结尾
        reordered = [scored[0][1]]
        
        if len(scored) > 2:
            middle = [item for _, item in scored[1:-1]]
            reordered.extend(middle)
        
        reordered.append(scored[-1][1])
        
        return reordered
    
    @staticmethod
    def split_context_for_attention(
        context: str,
        max_head_size: int = 8000,
        max_tail_size: int = 8000
    ) -> str:
        """
        将上下文分为开头和结尾两部分,舍弃中间
        
        利用LLM对首尾注意力更强的特性
        """
        tokens = context.split()
        
        if len(tokens) <= max_head_size + max_tail_size:
            return context
        
        head = ' '.join(tokens[:max_head_size])
        tail = ' '.join(tokens[-max_tail_size:])
        
        return f"""{head}
 
[... 内容已截断以保持上下文完整性 ...]
 
{tail}"""

八、综合实战模板

完整标记系统配置

MARKER_SYSTEM_CONFIG = {
    'section_delimiter': '════════════════════════════════════',
    'item_delimiter': '─' * 40,
    'source_format': '[来源: {title} | {date}]',
    'quality_markers': ['🟢', '🟡', '🔴'],
    'priority_markers': ['🔴', '🟠', '🟡', '🟢'],
    'attention_markers': {
        'start': '【',
        'end': '】'
    }
}
 
class ComprehensiveMarkerSystem:
    """综合标记系统"""
    
    def __init__(self, config: dict = None):
        self.config = config or MARKER_SYSTEM_CONFIG
        self.source_tracker = SourceTracker()
    
    def build_context(
        self,
        sections: list,
        query: str,
        include_sources: bool = True,
        include_quality: bool = True
    ) -> str:
        """构建完整的带标记上下文"""
        result = []
        
        # 1. 查询信息
        result.append(f"## 用户查询\n{query}\n")
        
        # 2. 重排sections(按相关性和优先级)
        reordered = PositionOptimizer.reorder_for_llm(sections, query)
        
        # 3. 遍历sections
        for i, section in enumerate(reordered, 1):
            result.append(self.config['section_delimiter'])
            result.append(f"[第{i}部分] {section.get('title', 'Untitled')}")
            result.append(self.config['section_delimiter'])
            
            # 优先级标记
            if 'priority' in section:
                priority_idx = section['priority']
                if 0 <= priority_idx < len(self.config['priority_markers']):
                    marker = self.config['priority_markers'][priority_idx]
                    result.append(f"{marker} 优先级: {['P0-紧急', 'P1-高', 'P2-中', 'P3-低'][priority_idx]}")
            
            # 内容
            result.append(section.get('content', ''))
            
            # 来源标注
            if include_sources and 'source' in section:
                source = section['source']
                source_tag = f"[来源: {source.get('title', 'Unknown')}"
                if source.get('date'):
                    source_tag += f" | {source['date']}"
                source_tag += "]"
                result.append(source_tag)
            
            # 质量标记
            if include_quality and 'reliability' in section:
                rel_idx = {'high': 0, 'medium': 1, 'low': 2}.get(
                    section['reliability'], 0
                )
                result.append(f"{self.config['quality_markers'][rel_idx]} 可信度: {section['reliability']}")
            
            result.append("")
        
        return "\n".join(result)
 
# 使用示例
system = ComprehensiveMarkerSystem()
 
sections = [
    {
        'title': '系统架构概述',
        'content': '系统采用微服务架构,支持水平扩展...',
        'priority': 1,
        'source': {'title': '技术文档v1.2', 'date': '2024-01'},
        'reliability': 'high'
    },
    {
        'title': '部署流程',
        'content': '详细部署步骤如下...',
        'priority': 2,
        'source': {'title': '运维手册', 'date': '2023-12'},
        'reliability': 'medium'
    },
    {
        'title': '故障排除',
        'content': '常见问题及解决方案...',
        'priority': 0,  # 最高优先级
        'source': {'title': '经验总结', 'date': '2024-02'},
        'reliability': 'medium'
    }
]
 
context = system.build_context(
    sections=sections,
    query="如何部署系统",
    include_sources=True,
    include_quality=True
)
 
print(context)

一图总结

┌─────────────────────────────────────────────────────────────┐
│              分隔符与标记系统速查表                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  📏 分隔符                                                 │
│  ├─ 通用: ---, ***                                         │
│  ├─ 强分隔: ═════, ────                                   │
│  └─ 卡片: ┌─┐ ┌─┐                                        │
│                                                             │
│  🏷️ 标记类型                                              │
│  ├─ 来源: [来源: 文档名 | 日期]                             │
│  ├─ 质量: 🟢高 🟡中 🔴低                                  │
│  ├─ 优先级: 🔴P0 🟠P1 🟡P2 🟢P3                          │
│  └─ 时效: ⏰实时 📅近期 📆中期 📜历史                       │
│                                                             │
│  🎯 最佳实践                                               │
│  ├─ 重要内容放首尾(解决Lost in Middle)                    │
│  ├─ 使用一致的标记风格                                      │
│  ├─ 按优先级排序sections                                   │
│  └─ 来源标注让答案可溯源                                    │
│                                                             │
└─────────────────────────────────────────────────────────────┘

相关主题


参考文献

  1. Liu, N. F., et al. (2024). Lost in the Middle: How Language Models Use Long Contexts.
  2. Clark, K., et al. (2020). ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators.
  3. Raffel, C., et al. (2020). Exploring the Limits of Transfer Learning with T5.
  4. Vaswani, A., et al. (2017). Attention Is All You Need.