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

运行REBEL关系抽取代码报TypeError无法转换为Sequence错误求解

错误原因

这个报错是transformers库版本迭代带来的API不兼容问题导致的:

  • 你运行的是REBEL官方给出的旧版示例代码,适配的是4.28版本之前的transformers。新版transformers对text2text-generation类型的pipeline返回结构、参数做了调整:
    1. 原代码中传入的return_tensors=True会让pipeline返回封装好的张量字典,而非预期的包含token id序列的普通字典,返回结果中不存在代码要取的generated_token_ids键,反而出现了内部用的output_ids字段
    2. return_text=False参数在新版中已经被弃用,不再生效
  • 后续batch_decode尝试解析传入的字典对象而非token id序列时,就会抛出无法将字典转换为序列的类型错误。
修复方法

两种方案选其一即可:

方案1:适配新版transformers(推荐)

修改pipeline调用部分的代码,去掉失效参数,修正取值逻辑,同时补充max_new_tokens参数避免生成内容被截断,顺便修正原解析函数中重复定义relation变量的笔误:

from transformers import pipeline

triplet_extractor = pipeline('text2text-generation', model='Babelscape/rebel-large', tokenizer='Babelscape/rebel-large')

# 修正后的调用逻辑
input_text = "Punta Cana is a resort town in the municipality of Higuey, in La Altagracia Province, the eastern most province of the Dominican Republic"
gen_output = triplet_extractor(input_text, max_new_tokens=256, return_tensors=False)[0]
extracted_text = triplet_extractor.tokenizer.batch_decode([gen_output["generated_token_ids"]])
print(extracted_text[0])

# 修正笔误后的三元组解析函数
def extract_triplets(text):
    triplets = []
    subject, relation, object_ = '', '', ''
    text = text.strip()
    current = 'x'
    for token in text.replace("<s>", "").replace("<pad>", "").replace("</s>", "").split():
        if token == "<triplet>":
            current = 't'
            if relation != '':
                triplets.append({'head': subject.strip(), 'type': relation.strip(),'tail': object_.strip()})
                relation = ''
            subject = ''
        elif token == "<subj>":
            current = 's'
            if relation != '':
                triplets.append({'head': subject.strip(), 'type': relation.strip(),'tail': object_.strip()})
            object_ = ''
        elif token == "<obj>":
            current = 'o'
            relation = ''
        else:
            if current == 't':
                subject += ' ' + token
            elif current == 's':
                object_ += ' ' + token
            elif current == 'o':
                relation += ' ' + token
    if subject != '' and relation != '' and object_ != '':
        triplets.append({'head': subject.strip(), 'type': relation.strip(),'tail': object_.strip()})
    return triplets
extracted_triplets = extract_triplets(extracted_text[0])
print(extracted_triplets)

方案2:降级transformers到兼容版本

如果不想修改代码,直接将transformers库降级到和原示例适配的版本即可,执行以下安装命令:

pip install transformers==4.27.4

降级完成后原代码可直接运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:18:15