Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Langchain ai Langchain BaseTool Invoke

From Leeroopedia
Knowledge Sources
Domains Agentic_AI, Tool_Use
Last Updated 2026-02-11 00:00 GMT

Overview

Concrete tool for executing LLM-requested tool calls and creating ToolMessage results provided by langchain-core.

Description

BaseTool.invoke() executes a tool by accepting a ToolCall object (or string/dict) from the model's response. It validates the input against the tool's args_schema, calls the _run() method, and handles errors via handle_tool_error. The result is then wrapped in a ToolMessage with the matching tool_call_id.

Usage

Use BaseTool.invoke() with the ToolCall objects from AIMessage.tool_calls. Create ToolMessage objects to feed results back to the model.

Code Reference

Source Location

  • Repository: langchain
  • File: libs/core/langchain_core/tools/base.py (BaseTool.invoke), libs/core/langchain_core/messages/tool.py (ToolMessage)
  • Lines: base.py L405-1100+ (BaseTool class); tool.py L26-120 (ToolMessage)

Signature

# BaseTool.invoke
def invoke(
    self,
    input: str | dict | ToolCall,
    config: RunnableConfig | None = None,
    **kwargs: Any,
) -> Any:

# ToolMessage
class ToolMessage(BaseMessage, ToolOutputMixin):
    tool_call_id: str
    type: Literal["tool"] = "tool"
    artifact: Any = None

Import

from langchain_core.tools import BaseTool
from langchain_core.messages import ToolMessage

I/O Contract

Inputs

Name Type Required Description
input str or dict or ToolCall Yes Tool call from AIMessage.tool_calls
config RunnableConfig or None No Run configuration for tracing

Outputs

Name Type Description
return Any Tool execution result (string, dict, or structured data)

Usage Examples

Executing Tool Calls

from langchain_core.messages import ToolMessage, HumanMessage

# After receiving AIMessage with tool_calls:
ai_msg = llm_with_tools.invoke([HumanMessage(content="What's the weather?")])

tool_messages = []
for tool_call in ai_msg.tool_calls:
    # Find and execute the tool
    result = get_weather.invoke(tool_call)
    tool_messages.append(
        ToolMessage(
            content=str(result),
            tool_call_id=tool_call["id"],
            name=tool_call["name"],
        )
    )

Related Pages

Implements Principle

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment