使用LangChain调用通义大模型实现流式输出时遇TypeError报错求助
解决LangChain调用通义大模型流式输出的TypeError问题
问题原因
你遇到的TypeError: Additional kwargs key output_tokens already exists in left dict and value has unsupported type <class 'int'>错误,核心原因是使用了基础LLM类Tongyi搭配聊天模型专用的ChatPromptTemplate,两者的输入输出格式不匹配,导致流式返回的字段处理冲突。
解决方案
替换基础LLM类Tongyi为聊天模型类ChatTongyi,并调整代码适配聊天模型的调用逻辑:
修正后的代码
# from dotenv import load_dotenv from langchain.prompts import ChatPromptTemplate from langchain_community.chat_models import ChatTongyi # load_dotenv() # 使用ChatTongyi聊天模型类,启用流式输出 chat_model = ChatTongyi(streaming=True, max_tokens=2048) prompt = ChatPromptTemplate.from_messages( [("system", "你是一个专业的AI助手。"), ("human", "{query}")] ) llm_chain = prompt | chat_model # 流式遍历返回的ChatMessageChunk ret = llm_chain.stream({"query": "你是谁?"}) for chunk in ret: print(chunk.content, end="", flush=True) print()
关键改动说明
- 替换
langchain_community.llms.Tongyi为langchain_community.chat_models.ChatTongyi:ChatTongyi是专门适配聊天场景的模型类,与ChatPromptTemplate的格式完全兼容,能正确处理流式返回的字段。 - 遍历输出时取
chunk.content:聊天模型流式返回的是ChatMessageChunk对象,需要提取content属性获取文本内容。
额外注意事项
- 确保
langchain和langchain_community版本为最新稳定版,避免因版本兼容问题导致的异常:pip install --upgrade langchain langchain_community - 确认环境变量中已配置
DASHSCOPE_API_KEY(通义API密钥),可通过load_dotenv()加载本地.env文件,或直接设置系统环境变量。
内容的提问来源于stack exchange,提问作者hao chen
相关产品推荐
相关产品推荐

