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)