Overview
TheuseToolExecutor hook automatically parses LLM responses and executes file system operations when the response contains valid tool instructions in JSON format. It processes actions like creating, reading, writing, and deleting files.
Import
Usage
Parameters
The LLM response to parse for tool instructions. Typically comes from the
useChat hook’s answer state.The hook expects JSON-formatted instructions in the format:Loading state from the chat hook. The tool executor only processes actions when
loading is false, ensuring the LLM response is complete.Return Value
Currently returns an empty string. This value is maintained for future extensibility to return execution results or status information.
Supported Actions
The hook supports the following file system actions:create_file
Creates a new file with the specified content.read_file
Reads and logs the contents of a file to the console.write_file
Writes content to an existing file (overwrites existing content).delete_file
Deletes the specified file.Behavior
The hook uses auseEffect that:
- Waits for completion: Returns early if
loadingistrue - Cleans the response: Removes code block markers (backticks) and trims whitespace
- Validates JSON: Checks if the cleaned response starts with
{and ends with} - Parses instructions: Attempts to parse the cleaned response as JSON
- Validates action: Ensures the parsed object has an
actionproperty - Executes tool: Calls the appropriate file system function based on the action
- Error handling: Catches and logs parsing or execution errors to the console
Error Handling
Errors during tool execution are caught and logged to the console:- Invalid JSON in the response
- Missing required fields (
action,file,content) - File system operation failures
- Responses that don’t contain tool instructions
Integration with useChat
Typical usage pattern withuseChat:
Implementation Details
The hook integrates with file system utilities:createFile()fromtools/createFile.jsreadFile()fromtools/readFile.jswriteFile()fromtools/writeFile.jsdeleteFile()fromtools/deleteFile.js
loading or answer changes.
Source: /workspace/source/src/hooks/useToolExecutor.ts:8