You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查LLM分类输出完整性并按需重试?LangChain链选型困惑

解决LLM多类别标注遗漏问题的实现方案

核心需求

给LLM提供37个固定类别,对调研文本做多类别标注并输出Markdown表格。需自动检查返回结果是否覆盖所有类别:

  • 若所有类别都存在,流程结束
  • 若存在遗漏,让LLM补全遗漏类别的标注(或重新执行分类)

实现思路

无需使用RouterChain或SequentialChain,用条件判断+循环的方式更直接可控,核心步骤:

  1. 调用LLM生成初始分类表格
  2. 解析返回的Markdown表格,提取已处理的类别
  3. 对比原始类别列表,筛选出遗漏的类别
  4. 若有遗漏,生成补全提示让LLM仅处理遗漏类别;无遗漏则终止流程

完整代码实现

from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
import markdown_it

# 初始化LLM
chat = ChatOpenAI(temperature=0, model_name='gpt-4')

# 配置参数
survey_response = 'example response'
all_classes = ['class 1', 'class 2', 'class 3', 'class 4']  # 替换为你的37个类别

# 初始分类提示模板
initial_template = """这里是一份调研问题的回复,我需要对它做主题分析,将其归类到预定义的类别中。

回复内容:
####{response}####

请判断该回复是否属于以下每个类别,输出格式为Markdown表格,包含4列:
1) class:类别名称
2) is_member:1/0,表示回复是否属于该类别
3) confidence_score:置信度,可选值为low(0-20%)、medium(50%-80%)、high(80%+)
4) excerpt:支持该分类的回复片段

类别列表:
####{classes}####
"""

# 补全分类提示模板
completion_template = """之前对调研回复的分类遗漏了部分类别,请仅针对以下遗漏的类别完成标注,输出格式要求与之前一致:

回复内容:
####{response}####

遗漏的类别:
####{missing_classes}####

请输出仅包含这些遗漏类别的Markdown表格。
"""

def parse_markdown_table(markdown_text):
    """解析LLM返回的Markdown表格,提取所有已处理的类别"""
    parser = markdown_it.MarkdownIt()
    tokens = parser.parse(markdown_text)
    
    processed_classes = []
    in_table = False
    for token in tokens:
        if token.type == 'table_open':
            in_table = True
            continue
        if token.type == 'table_close':
            in_table = False
            break
        if in_table and token.type == 'inline' and token.children:
            class_name = token.children[0].content.strip()
            if class_name != 'class':  # 跳过表头
                processed_classes.append(class_name)
    return processed_classes

def merge_tables(original_table, completion_table):
    """合并初始表格和补全表格"""
    return original_table + "\n\n" + completion_table

# 主流程
def run_multiclass_classification():
    # 初始分类请求
    initial_prompt = ChatPromptTemplate.from_template(initial_template)
    initial_input = initial_prompt.format_messages(
        response=survey_response,
        classes="\n".join(all_classes)
    )
    llm_result = chat(initial_input).content
    
    # 解析已处理的类别
    processed_classes = parse_markdown_table(llm_result)
    
    # 检查是否有遗漏
    missing_classes = [cls for cls in all_classes if cls not in processed_classes]
    
    if not missing_classes:
        print("所有类别已完整标注:")
        print(llm_result)
        return llm_result
    else:
        print(f"发现遗漏类别:{missing_classes},开始补全...")
        # 生成补全请求
        completion_prompt = ChatPromptTemplate.from_template(completion_template)
        completion_input = completion_prompt.format_messages(
            response=survey_response,
            missing_classes="\n".join(missing_classes)
        )
        completion_result = chat(completion_input).content
        
        # 合并表格
        final_result = merge_tables(llm_result, completion_result)
        print("补全后的完整标注:")
        print(final_result)
        return final_result

# 执行
run_multiclass_classification()

关键说明

  • 表格解析:使用markdown-it解析LLM返回的Markdown结构,确保准确提取已处理的类别
  • 补全逻辑:仅让LLM处理遗漏类别,减少重复计算和Token消耗
  • 灵活性:若补全仍有遗漏,可在主流程中加入循环,直到所有类别都被覆盖

内容的提问来源于stack exchange,提问作者codeananda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:01:26