使用LLM与Chat Prompt Template构建聊天机器人遇len()类型错误求助
错误分析与解决:TypeError: object of type ChatPromptValue has no len()
错误成因
你使用的是基础纯文本LLM(Llama),但搭配了ChatPromptTemplate模板。ChatPromptTemplate生成的是ChatPromptValue对象(包含聊天消息结构),而基础LLM仅支持纯字符串输入。当框架尝试计算ChatPromptValue的长度时,就会触发TypeError。本质是Prompt类型与模型类型不匹配。
解决方法
方法1:改用纯文本PromptTemplate
既然你的Prompt本身是纯文本格式,无需聊天消息结构,直接替换为PromptTemplate即可:
from langchain.prompts import PromptTemplate prompt = PromptTemplate.from_template( ''' Answer the following question based on the provided context only. Please provide the most accurate response based on question and context. If you don't know the answer don't makeup the answer just mention that you dont have enough information. I'll tip you $1000 if user finds it helpful. <context> {context} </context> Questions:{input} ''' )
方法2:将基础Llama包装为聊天模型
若坚持使用ChatPromptTemplate,需把基础Llama包装成支持聊天消息的ChatLlama模型,使其能处理ChatPromptValue对象:
from langchain.chat_models import ChatLlama llm = ChatLlama( model_path=model_path1, n_gqa=8, n_ctx=16000, n_threads=32, n_gpu_layers=0, generation_kwargs=generation_kwargs # 传入之前定义的生成参数 )
额外注意
你定义的generation_kwargs在原代码中未被使用,需确保将其关联到模型或链的配置中,否则生成参数不会生效。
内容的提问来源于stack exchange,提问作者Porselvan Prakash
相关产品推荐
相关产品推荐

