使用KeyLLM结合Langchain时出现'tuple'无'page_content'属性错误
解决KeyLLM关键词提取报错问题
错误原因分析
第一个错误:'tuple' object has no attribute 'page_content'
你导入的from keybert.llm import OpenAI类与KeyLLM存在兼容性问题,初始化后的LLM实例返回格式不符合预期,导致处理单个字符串文档时,内部逻辑错误将其解析为tuple类型,触发LangChain模板的属性访问报错。
第二个错误:TypeError: replace() argument 2 must be str, not Document
KeyLLM的extract_keywords方法仅接受字符串或字符串列表作为输入,无需转换为LangChain的Document对象,直接传入Document会导致字符串替换操作失败。
修复方案
步骤1:替换正确的LLM导入
使用LangChain官方的OpenAI类而非KeyBert封装的版本,确保与KeyLLM的兼容性。
步骤2:使用正确的输入格式
直接传入字符串或字符串列表,无需转换为Document对象。
完整修复代码
import openai from langchain.llms import OpenAI from keybert import KeyLLM # 配置OpenAI密钥 openai.api_key = "sk-..." # 初始化LangChain的OpenAI实例(指定兼容的文本补全模型) llm = OpenAI( model_name="gpt-3.5-turbo-instruct", openai_api_key=openai.api_key, temperature=0 # 降低随机性,提升关键词稳定性 ) # 加载KeyLLM kw_model = KeyLLM(llm) # 提取关键词(支持单个字符串或字符串列表) document = "The website mentions that it only takes a couple of days to deliver but I still have not received mine." keywords = kw_model.extract_keywords(document) print(keywords)
额外说明
- 处理多个文档时,直接传入字符串列表即可:
documents = [ "The website mentions that it only takes a couple of days to deliver but I still have not received mine.", "AI-powered keyword extraction tools simplify content analysis tasks." ] keywords_list = kw_model.extract_keywords(documents) - 若使用GPT-4等模型,需对应调整
model_name参数,确保模型支持文本补全接口。
内容的提问来源于stack exchange,提问作者Jjnish
相关产品推荐
相关产品推荐

