如何解决AttributeError: 'bytes'对象无'page_content'属性问题
解决AttributeError: 'bytes' object has no attribute 'page_content'错误
错误原因
Chroma.from_documents()要求传入LangChain Document对象的列表,但你的代码中直接将文件读取的bytes内容传入,bytes对象没有page_content属性,导致触发该错误。
修复步骤
- 导入LangChain的
Document类,用于包装文本内容 - 修改文件读取函数,将bytes内容转成字符串,并封装为Document对象
- 确保传入Chroma的是Document对象列表
修改后的完整代码
from langchain.prompts import ChatPromptTemplate from langchain_community.chat_models import ChatOllama from langchain.embeddings import SentenceTransformerEmbeddings import streamlit as st from langchain.vectorstores import Chroma from langchain_core.runnables import RunnablePassthrough from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate # 新增导入Document类 from langchain_core.documents.base import Document # Initialize the chat model model_local = ChatOllama(model="mistral") # 修改load_document函数,返回Document对象 def load_document(c_file): if c_file is not None: # 读取bytes并转成字符串,编码可根据实际C文件编码调整 file_contents = c_file.read().decode("utf-8") # 封装为Document对象,page_content字段存储文本内容 return Document(page_content=file_contents) else: return None # Define function to generate response def generate_response(query, document): if document: # 传入单个Document对象组成的列表 documents = [document] embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2") vectorstore = Chroma.from_documents(documents, embeddings) retriever = vectorstore.as_retriever() after_rag_template = """Answer the question based only on the following context: {context} Question: {question} """ after_rag_prompt = ChatPromptTemplate.from_template(after_rag_template) after_rag_chain = ( {"context": retriever, "question": RunnablePassthrough()} | after_rag_prompt | model_local | StrOutputParser() ) response = after_rag_chain.invoke(query) return response else: return "Please upload a C file." # Define the Streamlit app def main(): st.set_page_config(page_title="Unit Test Case Generator", layout="centered") #st.title("Unit Test Case Generator") # Sidebar for uploading C file st.sidebar.title("Upload C File") c_file = st.sidebar.file_uploader("Choose a C file", type=["c"]) # Text box for entering query query = st.text_area("Enter your query:") # Submit button if st.button("Submit") and query: document = load_document(c_file) response = generate_response(query, document) st.subheader("Generated Output C File:") if response: st.code(response, language='c') else: st.warning("No response generated.") if __name__ == "__main__": main()
关键修改说明
- 新增
from langchain_core.documents.base import Document导入语句,引入LangChain标准的文档包装类 - 修改
load_document函数:将文件读取的bytes数据转为字符串,再封装成Document对象,满足Chroma的输入要求 - 保持后续逻辑不变,因为现在传入的已经是符合要求的Document对象列表
内容的提问来源于stack exchange,提问作者Anjali Kumari
相关产品推荐
相关产品推荐

