Home / File/ output_parser.py — langchain Source File

output_parser.py — langchain Source File

Architecture documentation for output_parser.py, a python file in the langchain codebase. 5 imports, 0 dependents.

Entity Profile

Dependency Diagram

graph LR
  85cecf33_0d6f_a098_d3d1_005b3319a371["output_parser.py"]
  67ec3255_645e_8b6e_1eff_1eb3c648ed95["re"]
  85cecf33_0d6f_a098_d3d1_005b3319a371 --> 67ec3255_645e_8b6e_1eff_1eb3c648ed95
  80d582c5_7cc3_ac96_2742_3dbe1cbd4e2b["langchain_core.agents"]
  85cecf33_0d6f_a098_d3d1_005b3319a371 --> 80d582c5_7cc3_ac96_2742_3dbe1cbd4e2b
  75137834_4ba7_dc43_7ec5_182c05eceedf["langchain_core.exceptions"]
  85cecf33_0d6f_a098_d3d1_005b3319a371 --> 75137834_4ba7_dc43_7ec5_182c05eceedf
  e160f068_75de_4342_6673_9969b919de85["langchain_classic.agents.agent"]
  85cecf33_0d6f_a098_d3d1_005b3319a371 --> e160f068_75de_4342_6673_9969b919de85
  eb534928_e458_f4bd_11f5_98615ecb3ea7["langchain_classic.agents.mrkl.prompt"]
  85cecf33_0d6f_a098_d3d1_005b3319a371 --> eb534928_e458_f4bd_11f5_98615ecb3ea7
  style 85cecf33_0d6f_a098_d3d1_005b3319a371 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

import re

from langchain_core.agents import AgentAction, AgentFinish
from langchain_core.exceptions import OutputParserException

from langchain_classic.agents.agent import AgentOutputParser
from langchain_classic.agents.mrkl.prompt import FORMAT_INSTRUCTIONS

FINAL_ANSWER_ACTION = "Final Answer:"
MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE = (
    "Invalid Format: Missing 'Action:' after 'Thought:"
)
MISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE = (
    "Invalid Format: Missing 'Action Input:' after 'Action:'"
)
FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE = (
    "Parsing LLM output produced both a final answer and a parse-able action:"
)


class MRKLOutputParser(AgentOutputParser):
    """MRKL Output parser for the chat agent."""

    format_instructions: str = FORMAT_INSTRUCTIONS
    """Default formatting instructions"""

    def get_format_instructions(self) -> str:
        """Returns formatting instructions for the given output parser."""
        return self.format_instructions

    def parse(self, text: str) -> AgentAction | AgentFinish:
        """Parse the output from the agent into an AgentAction or AgentFinish object.

        Args:
            text: The text to parse.

        Returns:
            An AgentAction or AgentFinish object.

        Raises:
            OutputParserException: If the output could not be parsed.
        """
        includes_answer = FINAL_ANSWER_ACTION in text
        regex = (
            r"Action\s*\d*\s*:[\s]*(.*?)[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
        )
        action_match = re.search(regex, text, re.DOTALL)
        if action_match and includes_answer:
            if text.find(FINAL_ANSWER_ACTION) < text.find(action_match.group(0)):
                # if final answer is before the hallucination, return final answer
                start_index = text.find(FINAL_ANSWER_ACTION) + len(FINAL_ANSWER_ACTION)
                end_index = text.find("\n\n", start_index)
                return AgentFinish(
                    {"output": text[start_index:end_index].strip()},
                    text[:end_index],
                )
            msg = f"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}"
            raise OutputParserException(msg)

        if action_match:
            action = action_match.group(1).strip()
            action_input = action_match.group(2)
            tool_input = action_input.strip(" ")
            # ensure if its a well formed SQL query we don't remove any trailing " chars
            if tool_input.startswith("SELECT ") is False:
                tool_input = tool_input.strip('"')

            return AgentAction(action, tool_input, text)

        if includes_answer:
            return AgentFinish(
                {"output": text.rsplit(FINAL_ANSWER_ACTION, maxsplit=1)[-1].strip()},
                text,
            )

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

    @property
    def _type(self) -> str:
        return "mrkl"

Subdomains

Dependencies

  • langchain_classic.agents.agent
  • langchain_classic.agents.mrkl.prompt
  • langchain_core.agents
  • langchain_core.exceptions
  • re

Frequently Asked Questions

What does output_parser.py do?
output_parser.py is a source file in the langchain codebase, written in python. It belongs to the AgentOrchestration domain, ActionLogic subdomain.
What does output_parser.py depend on?
output_parser.py imports 5 module(s): langchain_classic.agents.agent, langchain_classic.agents.mrkl.prompt, langchain_core.agents, langchain_core.exceptions, re.
Where is output_parser.py in the architecture?
output_parser.py is located at libs/langchain/langchain_classic/agents/mrkl/output_parser.py (domain: AgentOrchestration, subdomain: ActionLogic, directory: libs/langchain/langchain_classic/agents/mrkl).

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free