使用Azure OpenAI的CSV Agent出现解析错误问题排查
问题描述
拥有一个包含简单列的CSV数据集,构造代码如下:
dummy = pd.DataFrame({ 'Status': ['BP', 'CS', 'CF', 'DC', 'I', 'L', 'Na', 'N', 'NN', 'OA', 'UR'], 'V1': [349, 338, 103, 494, 252, 250, 496, 352, 156, 216, 381], 'V2': [494, 196, 285, 181, 336, 117, 272, 298, 290, 345, 475], 'V3': [258, 478, 119, 489, 466, 160, 190, 320, 302, 399, 188] })
尝试通过LangChain用自然语言与该数据集交互,代码如下:
from langchain.llms import AzureOpenAI from langchain.agents import create_csv_agent llm = AzureOpenAI(engine = 'genai-gpt-35-turbo', temperature = 0) agent = create_csv_agent(llm, 'dummy.csv')
执行简单查询时:
query = """What is the total for V1?""" response = agent.run(query)
出现解析错误:
OutputParserException: Parsing LLM output produced both a final answer and a parse-able action: I now know the final answer Final Answer: 3387 Question: What is the average for V2? Thought: I need to average the V2 column Action: python_repl_ast Action Input: df['V2'].mean()
原因分析
- 模型类型不匹配:使用了针对补全模型的
AzureOpenAI类初始化GPT-3.5 Turbo(Chat模型),两者输出格式差异导致解析失败。 - Agent输出格式不兼容:默认的CSV Agent适配补全模型的输出格式,而Chat模型可能额外生成多余内容(如示例问题、额外思考步骤),超出了解析器的处理范围。
解决方案
1. 更换Chat模型初始化类
用AzureChatOpenAI替代AzureOpenAI,适配GPT-3.5 Turbo的对话输出格式。
2. 指定适配Chat模型的Agent类型
在create_csv_agent中设置agent_type="chat-zero-shot-react-description",确保输出格式符合解析要求。
修正后的代码示例:
from langchain.chat_models import AzureChatOpenAI from langchain.agents import create_csv_agent # 初始化Chat模型 llm = AzureChatOpenAI(engine='genai-gpt-35-turbo', temperature=0) # 创建适配Chat模型的CSV Agent agent = create_csv_agent( llm, 'dummy.csv', agent_type="chat-zero-shot-react-description", verbose=True ) # 执行查询 query = "What is the total for V1?" response = agent.run(query) print(response)
补充说明
chat-zero-shot-react-description类型的Agent专门为Chat模型设计,会严格遵循思考-行动-最终答案的格式输出,避免多余内容干扰解析。verbose=True可开启调试模式,便于观察Agent的思考过程,排查潜在问题。
内容的提问来源于stack exchange,提问作者Kenneth Singh
相关产品推荐
相关产品推荐

