Home / File/ output_parsers.py — langchain Source File

output_parsers.py — langchain Source File

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

File python LangChainCore MessageInterface 6 imports 2 functions 1 classes

Entity Profile

Dependency Diagram

graph LR
  3702dbed_edb1_9f35_9019_2f747b6a4112["output_parsers.py"]
  feec1ec4_6917_867b_d228_b134d0ff8099["typing"]
  3702dbed_edb1_9f35_9019_2f747b6a4112 --> feec1ec4_6917_867b_d228_b134d0ff8099
  9444498b_8066_55c7_b3a2_1d90c4162a32["langchain_core.messages"]
  3702dbed_edb1_9f35_9019_2f747b6a4112 --> 9444498b_8066_55c7_b3a2_1d90c4162a32
  4314bbaf_e703_b502_e912_6f6a39f2ab89["langchain_core.messages.tool"]
  3702dbed_edb1_9f35_9019_2f747b6a4112 --> 4314bbaf_e703_b502_e912_6f6a39f2ab89
  628cbc5d_711f_ac0c_2f53_db992d48d7da["langchain_core.output_parsers"]
  3702dbed_edb1_9f35_9019_2f747b6a4112 --> 628cbc5d_711f_ac0c_2f53_db992d48d7da
  4382dc25_6fba_324a_49e2_e9742d579385["langchain_core.outputs"]
  3702dbed_edb1_9f35_9019_2f747b6a4112 --> 4382dc25_6fba_324a_49e2_e9742d579385
  dd5e7909_a646_84f1_497b_cae69735550e["pydantic"]
  3702dbed_edb1_9f35_9019_2f747b6a4112 --> dd5e7909_a646_84f1_497b_cae69735550e
  style 3702dbed_edb1_9f35_9019_2f747b6a4112 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

"""Output parsers for Anthropic tool calls."""

from __future__ import annotations

from typing import Any, cast

from langchain_core.messages import AIMessage, ToolCall
from langchain_core.messages.tool import tool_call
from langchain_core.output_parsers import BaseGenerationOutputParser
from langchain_core.outputs import ChatGeneration, Generation
from pydantic import BaseModel, ConfigDict


class ToolsOutputParser(BaseGenerationOutputParser):
    """Output parser for tool calls."""

    first_tool_only: bool = False
    """Whether to return only the first tool call."""
    args_only: bool = False
    """Whether to return only the arguments of the tool calls."""
    pydantic_schemas: list[type[BaseModel]] | None = None
    """Pydantic schemas to parse tool calls into."""

    model_config = ConfigDict(
        extra="forbid",
    )

    def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
        """Parse a list of candidate model Generations into a specific format.

        Args:
            result: A list of `Generation` to be parsed. The Generations are assumed
                to be different candidate outputs for a single model input.
            partial: (Not used) Whether the result is a partial result. If `True`, the
                parser may return a partial result, which may not be complete or valid.

        Returns:
            Structured output.

        """
        if not result or not isinstance(result[0], ChatGeneration):
            return None if self.first_tool_only else []
        message = cast("AIMessage", result[0].message)
        tool_calls: list = [
            dict(tc) for tc in _extract_tool_calls_from_message(message)
        ]
        if isinstance(message.content, list):
            # Map tool call id to index
            id_to_index = {
                block["id"]: i
                for i, block in enumerate(message.content)
                if isinstance(block, dict) and block["type"] == "tool_use"
            }
            tool_calls = [{**tc, "index": id_to_index[tc["id"]]} for tc in tool_calls]
        if self.pydantic_schemas:
            tool_calls = [self._pydantic_parse(tc) for tc in tool_calls]
        elif self.args_only:
            tool_calls = [tc["args"] for tc in tool_calls]
        else:
            pass

        if self.first_tool_only:
            return tool_calls[0] if tool_calls else None
        return list(tool_calls)

    def _pydantic_parse(self, tool_call: dict) -> BaseModel:
        cls_ = {schema.__name__: schema for schema in self.pydantic_schemas or []}[
            tool_call["name"]
        ]
        return cls_(**tool_call["args"])


def _extract_tool_calls_from_message(message: AIMessage) -> list[ToolCall]:
    """Extract tool calls from a list of content blocks."""
    if message.tool_calls:
        return message.tool_calls
    return extract_tool_calls(message.content)


def extract_tool_calls(content: str | list[str | dict]) -> list[ToolCall]:
    """Extract tool calls from a list of content blocks."""
    if isinstance(content, list):
        tool_calls = []
        for block in content:
            if isinstance(block, str):
                continue
            if block["type"] != "tool_use":
                continue
            tool_calls.append(
                tool_call(name=block["name"], args=block["input"], id=block["id"]),
            )
        return tool_calls
    return []

Domain

Subdomains

Dependencies

  • langchain_core.messages
  • langchain_core.messages.tool
  • langchain_core.output_parsers
  • langchain_core.outputs
  • pydantic
  • typing

Frequently Asked Questions

What does output_parsers.py do?
output_parsers.py is a source file in the langchain codebase, written in python. It belongs to the LangChainCore domain, MessageInterface subdomain.
What functions are defined in output_parsers.py?
output_parsers.py defines 2 function(s): _extract_tool_calls_from_message, extract_tool_calls.
What does output_parsers.py depend on?
output_parsers.py imports 6 module(s): langchain_core.messages, langchain_core.messages.tool, langchain_core.output_parsers, langchain_core.outputs, pydantic, typing.
Where is output_parsers.py in the architecture?
output_parsers.py is located at libs/partners/anthropic/langchain_anthropic/output_parsers.py (domain: LangChainCore, subdomain: MessageInterface, directory: libs/partners/anthropic/langchain_anthropic).

Analyze Your Own Codebase

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

Try Supermodel Free