How to handle the tool call error without a middleware

In langchain, I can use a middleware like below to handle errors and return a TooMessage

@wrap_tool_call
def handle_tool_errors(request: ToolCallRequest, handler):
    try:
        return handler(request)
    except Exception as e:
        # Return a custom message to the model so it knows the tool failed
        return ToolMessage(
            content=f"Tool error: Please check your input and try again. ({str(e)})",
            tool_call_id=request.tool_call["id"]
        )

How to do this without a middleware ? Can I write the tool as the following ? But how can I get the tool call ID (or do I need this)?

@tool
@tool 
def read_text_file(filepath:str) -> dict:
    '''
    Read the file as text and return its content.
    Args:
        filepath: Absolute path to the file.
    '''
    if not os.path.isfile(filepath):
        return ToolMessage(status='error', content=f'{filepath} is not a file')
    
    with open(filepath, mode="r") as f:
        lines = f.readlines()
        content = ''.join(lines)
    return ToolMessage(status='success', content=content)

If you want to do this directly in the tool, you can return a ToolMessage as shown in your example. You can get the tool call ID from the injected ToolRuntime parameter:

import os
from langchain.tools import tool, ToolRuntime
from langchain.messages import ToolMessage


@tool
def read_text_file(filepath: str, runtime: ToolRuntime) -> ToolMessage:
    """Read the file as text and return its content.

    Args:
        filepath: Absolute path to the file.
    """
    if not os.path.isfile(filepath):
        return ToolMessage(
            content=f"Error: {filepath} is not a file.",
            tool_call_id=runtime.tool_call_id,
            status="error",
        )
    with open(filepath) as f:
        return ToolMessage(content=f.read(), tool_call_id=runtime.tool_call_id)

Hope that helps!

Docs: Tool return values

Thanks.