调用LLMGraphTransformer.convert_to_graph_documents触发AttributeError错误
问题:调用LLMGraphTransformer.convert_to_graph_documents触发AttributeError错误
在Colab Notebooks环境中,使用HuggingFaceH4/starchat2-15b-v0.1作为大语言模型,执行以下代码调用LLMGraphTransformer.convert_to_graph_documents方法时,触发AttributeError: 'str' object has no attribute 'content'错误:
from langchain_core.documents import Document text = """ Marie Curie, born in 1867, was a Polish and naturalised-French physicist and chemist who conducted pioneering research on radioactivity. She was the first woman to win a Nobel Prize, the first person to win a Nobel Prize twice, and the only person to win a Nobel Prize in two scientific fields. Her husband, Pierre Curie, was a co-winner of her first Nobel Prize, making them the first-ever married couple to win the Nobel Prize and launching the Curie family legacy of five Nobel Prizes. She was, in 1906, the first woman to become a professor at the University of Paris. """ documents = [Document(page_content=text)] graph_documents = llm_transformer.convert_to_graph_documents(documents) print(f"Nodes:{graph_documents[0].nodes}") print(f"Relationships:{graph_documents[0].relationships}")
错误栈信息:
AttributeError Traceback (most recent call last) <ipython-input-38-0a6a66b2d25f> in <cell line: 10>() 8 """ 9 documents = [Document(page_content=text)] ---> 10 graph_documents = llm_transformer.convert_to_graph_documents(documents) 11 print(f"Nodes:{graph_documents[0].nodes}") 12 print(f"Relationships:{graph_documents[0].relationships}") 2 frames /usr/local/lib/python3.10/dist-packages/langchain_experimental/graph_transformers/llm.py in process_response(self, document) 593 nodes_set = set() 594 relationships = [] ---> 595 parsed_json = self.json_repair.loads(raw_schema.content) 596 for rel in parsed_json: 597 # Nodes need to be deduplicated using a set AttributeError: 'str' object has no attribute 'content'
错误原因
langchain_experimental的LLMGraphTransformer在处理模型返回结果时,默认假设返回值是带有content属性的对象,但starchat2这类模型直接返回字符串,导致代码尝试访问raw_schema.content时触发属性错误。
解决办法
方法1:修改LLMGraphTransformer的process_response方法
找到langchain_experimental/graph_transformers/llm.py中的process_response函数,修改返回值处理逻辑,兼容字符串类型:
# 原代码行 parsed_json = self.json_repair.loads(raw_schema.content) # 修改为 raw_content = raw_schema.content if hasattr(raw_schema, 'content') else raw_schema parsed_json = self.json_repair.loads(raw_content)
方法2:给LLM添加返回值包装器
自定义包装类将字符串返回值转为带content属性的对象,避免修改源码:
class StringWrapper: def __init__(self, content): self.content = content # 替换LLM的predict方法 original_predict = llm.predict def wrapped_predict(prompt): result = original_predict(prompt) return StringWrapper(result) llm.predict = wrapped_predict
方法3:升级LangChain版本
后续版本的LangChain可能已修复该兼容性问题,执行升级命令:
pip install --upgrade langchain langchain_experimental
内容的提问来源于stack exchange,提问作者Weikun You
相关产品推荐
相关产品推荐

