15 April 2025

LangChain-Tools

by Carson Kempf

LangChain Tools


Overview

Tools are implemented as python functions

They contain a schema that defines

Chat models support tool calling

Creating a Tool

Hides input arguments


The Tool Interface

Runnables

Schema Attributes

Key Methods


Creating tools with the @tool decorator

from langchain_core.tools import tool

@tool
def multiply(a: int, b: int) -> int:
   """Multiply two numbers."""
   return a * b

How to create custom tools (come back to this)


Using the Tool

multiply.invoke({"a": 2, "b": 3})

Inspecting the Tool’s Arguments

print(multiply.name) # multiply
print(multiply.description) # Multiply two numbers.
print(multiply.args) 
# {
# 'type': 'object', 
# 'properties': {'a': {'type': 'integer'}, 'b': {'type': 'integer'}}, 
# 'required': ['a', 'b']
# }

InjectedToolArg

Inject the user_id at runtime

from langchain_core.tools import tool, InjectedToolArg

@tool
def user_specific_tool(input_data: str, user_id: InjectedToolArg) -> str:
    """Tool that processes input data."""
    return f"User {user_id} processed {input_data}"

RunnableConfig

from langchain_core.runnables import RunnableConfig

@tool
async def some_func(..., config: RunnableConfig) -> ...:
    """Tool that does something."""
    # do something with config
    ...

await some_func.ainvoke(..., config={"configurable": {"value": "some_value"}})

Toolkits

# Initialize a toolkit
toolkit = ExampleTookit(...)

# Get list of tools
tools = toolkit.get_tools()

Tool Calling


Overview


Key Concepts

Tool Creation

The @tool Decorator

Tool Binding

Tool Calling

Tool Execution


Workflow for tool calling:

# Tool creation
tools = [my_tool]
# Tool binding
model_with_tools = model.bind_tools(tools)
# Tool calling 
response = model_with_tools.invoke(user_input)
  1. Create a tool
  2. Pass the tool to the .bind_tools() method
    • The tool is passed as a list
  3. Call the tool using the model

Tool Creation

from langchain_core.tools import tool

@tool
def multiply(a: int, b: int) -> int:
    """Multiply a and b."""
    return a * b

Tool Binding

DeepSeek Documentation

model_with_tools = model.bind_tools(tools_list)
def multiply(a: int, b: int) -> int:
    """Multiply a and b.

    Args:
        a: first int
        b: second int
    """
    return a * b

llm_with_tools = tool_calling_model.bind_tools([multiply])

Tool Calling

Example Invocation and Model Response

result = llm_with_tools.invoke("What is 2 multiplied by 3?")


result.tool_calls
{'name': 'multiply', 'args': {'a': 2, 'b': 3}, 'id': 'xxx', 'type': 'tool_call'}

Calling Tools Using ToolNode (LangGraph)