Home / File/ tools.py — langchain Source File

tools.py — langchain Source File

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

File python AgentOrchestration ActionLogic 7 imports 2 functions

Entity Profile

Dependency Diagram

graph LR
  ed473e28_b1e7_7216_4f15_0d043bb4cb27["tools.py"]
  7025b240_fdc3_cf68_b72f_f41dac94566b["json"]
  ed473e28_b1e7_7216_4f15_0d043bb4cb27 --> 7025b240_fdc3_cf68_b72f_f41dac94566b
  2a7f66a7_8738_3d47_375b_70fcaa6ac169["logging"]
  ed473e28_b1e7_7216_4f15_0d043bb4cb27 --> 2a7f66a7_8738_3d47_375b_70fcaa6ac169
  cfe2bde5_180e_e3b0_df2b_55b3ebaca8e7["collections.abc"]
  ed473e28_b1e7_7216_4f15_0d043bb4cb27 --> cfe2bde5_180e_e3b0_df2b_55b3ebaca8e7
  8e2034b7_ceb8_963f_29fc_2ea6b50ef9b3["typing"]
  ed473e28_b1e7_7216_4f15_0d043bb4cb27 --> 8e2034b7_ceb8_963f_29fc_2ea6b50ef9b3
  80d582c5_7cc3_ac96_2742_3dbe1cbd4e2b["langchain_core.agents"]
  ed473e28_b1e7_7216_4f15_0d043bb4cb27 --> 80d582c5_7cc3_ac96_2742_3dbe1cbd4e2b
  d758344f_537f_649e_f467_b9d7442e86df["langchain_core.messages"]
  ed473e28_b1e7_7216_4f15_0d043bb4cb27 --> d758344f_537f_649e_f467_b9d7442e86df
  07acf81c_3473_eef9_7bd1_815539c71249["langchain_classic.agents.output_parsers.tools"]
  ed473e28_b1e7_7216_4f15_0d043bb4cb27 --> 07acf81c_3473_eef9_7bd1_815539c71249
  style ed473e28_b1e7_7216_4f15_0d043bb4cb27 fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

import json
import logging
from collections.abc import Sequence
from typing import Any

from langchain_core.agents import AgentAction
from langchain_core.messages import (
    AIMessage,
    BaseMessage,
    ToolMessage,
)

from langchain_classic.agents.output_parsers.tools import ToolAgentAction

_logger = logging.getLogger(__name__)


def _create_tool_message(
    agent_action: ToolAgentAction,
    observation: Any,
) -> ToolMessage:
    """Convert agent action and observation into a tool message.

    Args:
        agent_action: the tool invocation request from the agent.
        observation: the result of the tool invocation.

    Returns:
        ToolMessage that corresponds to the original tool invocation.

    Raises:
        ValueError: if the observation cannot be converted to a string.
    """
    if not isinstance(observation, str):
        try:
            content = json.dumps(observation, ensure_ascii=False)
        except TypeError:
            content = str(observation)
        except Exception:
            _logger.exception("Unexpected error converting observation to string.")
            content = str(observation)
    else:
        content = observation
    return ToolMessage(
        tool_call_id=agent_action.tool_call_id,
        content=content,
        additional_kwargs={"name": agent_action.tool},
    )


def format_to_tool_messages(
    intermediate_steps: Sequence[tuple[AgentAction, str]],
) -> list[BaseMessage]:
    """Convert (AgentAction, tool output) tuples into `ToolMessage` objects.

    Args:
        intermediate_steps: Steps the LLM has taken to date, along with observations.

    Returns:
        list of messages to send to the LLM for the next prediction.

    """
    messages = []
    for agent_action, observation in intermediate_steps:
        if isinstance(agent_action, ToolAgentAction):
            new_messages = [
                *list(agent_action.message_log),
                _create_tool_message(agent_action, observation),
            ]
            messages.extend([new for new in new_messages if new not in messages])
        else:
            messages.append(AIMessage(content=agent_action.log))
    return messages

Subdomains

Dependencies

  • collections.abc
  • json
  • langchain_classic.agents.output_parsers.tools
  • langchain_core.agents
  • langchain_core.messages
  • logging
  • typing

Frequently Asked Questions

What does tools.py do?
tools.py is a source file in the langchain codebase, written in python. It belongs to the AgentOrchestration domain, ActionLogic subdomain.
What functions are defined in tools.py?
tools.py defines 2 function(s): _create_tool_message, format_to_tool_messages.
What does tools.py depend on?
tools.py imports 7 module(s): collections.abc, json, langchain_classic.agents.output_parsers.tools, langchain_core.agents, langchain_core.messages, logging, typing.
Where is tools.py in the architecture?
tools.py is located at libs/langchain/langchain_classic/agents/format_scratchpad/tools.py (domain: AgentOrchestration, subdomain: ActionLogic, directory: libs/langchain/langchain_classic/agents/format_scratchpad).

Analyze Your Own Codebase

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

Try Supermodel Free