Langchain pandas agent – Azure OpenAI account – Azure

by
Ali Hasan
azure-active-directory azure-openai langchain llama-cpp-python openai-api

Quick Fix: Enclose the agent.run() call in a try-except block to catch any exceptions that may be raised. If an exception is raised, print the error message. If no exception is raised, print the final answer.

The Solutions:

Solution 2: AzureChatOpenAI

Instead of utilizing the AzureOpenAI LLM, this solution suggests switching to AzureChatOpenAI LLM. This change resolves the issue of the LLM output containing both a final answer and a parsable action.

from langchain.agents import create_pandas_dataframe_agent
from langchain.chat_models import AzureChatOpenAI

import os
import pandas as pd

import openai

df = pd.read_csv("iris.csv")

openai.api_type = "azure"
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_KEY"] = "OPENAI_API_KEY"
os.environ["OPENAI_API_BASE"] = "https:<OPENAI_API_BASE>.openai.azure.com/"
os.environ["OPENAI_API_VERSION"] = "<OPENAI_API_VERSION>"

llm = AzureChatOpenAI(
    openai_api_type="azure",
    deployment_name="<deployment_name>",
    model_name="<model_name>"
)

agent = create_pandas_dataframe_agent(llm, df, verbose=True)
agent.run("how many rows are there?")

Solution 3: Modified output_parser.py for Azure OpenAI account

The error you encountered is resolved by implementing the code snippet below in your output_parser.py file.

def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
    includes_answer = FINAL_ANSWER_ACTION in text
    regex = (
        r&quot;Action\s*\d*\s*:[\s]*(.*?)[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)&quot;
    )
    action_match = re.search(regex, text, re.DOTALL)
    if action_match and not includes_answer:
            if includes_answer:
                raise OutputParserException(
                    f&quot;{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}&quot;
                )
            action = action_match.group(1).strip()
            action_input = action_match.group(2)
            tool_input = action_input.strip(&quot; &quot;)
            # ensure if its a well formed SQL query we don&#39;t remove any trailing &quot; chars
            if tool_input.startswith(&quot;SELECT &quot;) is False:
                tool_input = tool_input.strip(&#39;&quot;&#39;)

            return AgentAction(action, tool_input, text)

    elif includes_answer:
        return AgentFinish(
            {&quot;output&quot;: text.split(FINAL_ANSWER_ACTION)[-1].strip()}, text
        )

    if not re.search(r&quot;Action\s*\d*\s*:[\s]*(.*?)&quot;, text, re.DOTALL):
        raise OutputParserException(
            f&quot;Could not parse LLM output: `{text}`&quot;,
            observation=MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE,
            llm_output=text,
            send_to_llm=True,
        )
    elif not re.search(

Q&A

How to fix the error in the code that you provided?

The error in the code may be caused by the LangChain agent’s execution to parse the LLM’s output. Use try-except block to catch any exceptions that may be raised.

Which LLM is recommended to be used with Langchain agents?

AzureChatOpenAI is recommended to be used with Langchain agents.

What is the reason behind the error ‘Parsing LLM output produced both a final answer and a parse-able action’?

The error ‘Parsing LLM output produced both a final answer and a parse-able action’ is caused by the logic of the output parser in the LangChain library.

Video Explanation:

The following video, titled "Langchain pandas agent Azure OpenAI account - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Welcome to Mixible, your go-to source for comprehensive and informative content covering a broad range of topics from Stack Exchange ...