1. 项目概述基于JSON模板的LLM信息提取系统在当今企业级AI应用场景中信息提取任务往往面临需求多变、领域广泛的核心痛点。以我参与过的金融合规项目为例团队曾同时处理合同审核、财报分析和客户投诉分类等12种不同类型的文档处理需求。传统做法是为每个场景单独开发定制化模型和提示词导致系统维护成本呈指数级增长。这套基于JSON模板的可插拔系统本质上是通过结构化描述动态Prompt生成的技术路线将业务规则定义权交还给领域专家。其核心创新点在于配置驱动业务人员通过JSON文件定义提取规则无需接触代码模型无关支持任意支持结构化输出的LLMGPT-4、Claude、Gemini等两阶段处理先定位关键段落再精确提取解决长文档处理难题关键提示系统特别适合处理法律合同、医疗记录、财务报告等具有明确结构的专业文档实测在保险理赔单处理场景中相比传统方法减少70%的定制开发工作量2. 核心设计解析2.1 元数据驱动架构系统的核心在于将业务逻辑抽象为三类元数据Purpose定义该模板的用途和目标{ purpose: 从采购合同中提取付款条款关键信息, scope: 识别付款方式、账期、违约金比例等字段 }Key Points列举需要关注的具体要素key_points: [ 付款方式电汇/信用证/承兑汇票, 账期如货到30日内, 分期付款的具体比例和时间节点 ]Examples包含正负样本的教学案例examples: { positive: 买方应在货物验收合格后15个工作日内支付90%货款, negative: 付款时间为货到后未明确具体天数 }2.2 动态Prompt生成机制Prompt引擎通过以下步骤实现动态组装上下文构建将purpose转换为任务背景描述def build_context(purpose): return f你是一名专业的{domain}分析师请根据以下要求执行任务 {purpose}。请特别注意{key_points}指令生成根据key_points生成具体操作指令def generate_instructions(key_points): points_str \n.join([f- {point} for point in key_points]) return f请逐项检查以下要素\n{points_str}格式约束注入JSON Schema确保输出结构schema { type: object, properties: { payment_method: {type: string}, payment_terms: {type: string} } }3. 关键技术实现3.1 结构化输出控制我们采用Pydantic模型强制数据规范from pydantic import BaseModel, Field class PaymentTerm(BaseModel): clause_text: str Field(description原文中具体的条款内容) days: int Field(description约定的付款天数) percentage: float Field(description付款比例, ge0, le100) class ContractAnalysis(BaseModel): contract_id: str payment_terms: List[PaymentTerm] risk_flags: List[str]实测表明结构化输出可使格式错误率从传统方法的35%降至2%以下。关键在于为每个字段添加详细的description使用类型约束如ge/le限制数值范围设置required字段确保完整性3.2 两阶段处理流程阶段一文档定位def locate_relevant_sections(doc_text, section_types): prompt f请识别文档中与以下类型相关的内容 {section_types} 返回格式{{section_type: text}} return llm_call(prompt)阶段二精确提取def extract_from_section(section_text, template): prompt template.render(section_text) return validate_output(llm_call(prompt))避坑指南长文档处理时建议设置max_tokens限制避免上下文截断。我们采用512token的滑动窗口重叠率设为15%3.3 动态Few-shot学习系统支持运行时加载案例库def inject_examples(template, case_db): examples case_db.query( domaintemplate.domain, label[positive, negative] ) template.examples examples return template典型案例注入效果{ example_type: negative, text: 甲方可随时调整付款时间, reason: 条款未明确具体时限存在资金风险 }4. 系统架构详解4.1 组件交互流程graph TD A[业务人员] --|上传| B(JSON模板库) B -- C[模板解析引擎] C -- D[Prompt组装器] D -- E[LLM网关] E -- F[结果验证器] F -- G[下游系统]4.2 核心模块实现模板注册中心class TemplateRegistry: def __init__(self): self.templates {} def add_template(self, domain: str, template: dict): validate_schema(template) # 校验JSON结构 self.templates[domain] template def get_template(self, domain: str): return deepcopy(self.templates.get(domain))输出验证器def validate_output(raw_output: str, schema: dict): try: data json.loads(raw_output) validate(instancedata, schemaschema) return data except Exception as e: log_error(fValidation failed: {str(e)}) return trigger_retry_mechanism()5. 实战优化技巧5.1 模板设计原则原子性每个模板只处理单一文档类型反例同时处理采购合同和销售合同正例分别创建purchase_contract.json和sales_contract.json渐进式复杂从简单字段开始迭代// v1.0 基础字段 { fields: [party_a, party_b] } // v2.0 增加逻辑校验 { validation: { party_a: 必须是中国大陆注册公司 } }5.2 性能优化方案缓存策略lru_cache(maxsize100) def get_template(domain: str): return registry.get_template(domain)批量处理def batch_process(docs, template): with ThreadPoolExecutor() as executor: results list(executor.map( lambda doc: extract_from_section(doc, template), docs )) return results5.3 常见问题排查字段缺失检查模板中的required字段定义确认LLM版本支持function calling格式错误验证JSON Schema是否包含所有可能值在description中添加明确示例语义偏差增加negative examples数量在purpose中强化业务约束6. 扩展应用场景6.1 医疗病历结构化{ domain: medical_records, fields: { diagnosis: { description: ICD-10标准诊断代码, examples: [J18.9 肺炎] }, medications: { type: array, items: { name: 药品通用名, dosage: 给药剂量 } } } }6.2 法律条款比对def compare_clauses(template, doc_a, doc_b): extracted_a extract_from_section(doc_a, template) extracted_b extract_from_section(doc_b, template) return DeepDiff(extracted_a, extracted_b)实际部署时我们在合同管理系统集成了该功能将律师的条款审查时间缩短了60%。