Write content to a file.
| 153 | |
| 154 | |
| 155 | class WriteTool(Tool): |
| 156 | """Write content to a file.""" |
| 157 | |
| 158 | def __init__(self, workspace_dir: str = "."): |
| 159 | """Initialize WriteTool with workspace directory. |
| 160 | |
| 161 | Args: |
| 162 | workspace_dir: Base directory for resolving relative paths |
| 163 | """ |
| 164 | self.workspace_dir = Path(workspace_dir).absolute() |
| 165 | |
| 166 | @property |
| 167 | def name(self) -> str: |
| 168 | return "write_file" |
| 169 | |
| 170 | @property |
| 171 | def description(self) -> str: |
| 172 | return ( |
| 173 | "Write content to a file. Will overwrite existing files completely. " |
| 174 | "For existing files, you should read the file first using read_file. " |
| 175 | "Prefer editing existing files over creating new ones unless explicitly needed." |
| 176 | ) |
| 177 | |
| 178 | @property |
| 179 | def parameters(self) -> dict[str, Any]: |
| 180 | return { |
| 181 | "type": "object", |
| 182 | "properties": { |
| 183 | "path": { |
| 184 | "type": "string", |
| 185 | "description": "Absolute or relative path to the file", |
| 186 | }, |
| 187 | "content": { |
| 188 | "type": "string", |
| 189 | "description": "Complete content to write (will replace existing content)", |
| 190 | }, |
| 191 | }, |
| 192 | "required": ["path", "content"], |
| 193 | } |
| 194 | |
| 195 | async def execute(self, path: str, content: str) -> ToolResult: |
| 196 | """Execute write file.""" |
| 197 | try: |
| 198 | file_path = Path(path) |
| 199 | # Resolve relative paths relative to workspace_dir |
| 200 | if not file_path.is_absolute(): |
| 201 | file_path = self.workspace_dir / file_path |
| 202 | |
| 203 | # Create parent directories if they don't exist |
| 204 | file_path.parent.mkdir(parents=True, exist_ok=True) |
| 205 | |
| 206 | file_path.write_text(content, encoding="utf-8") |
| 207 | return ToolResult(success=True, content=f"Successfully wrote to {file_path}") |
| 208 | except Exception as e: |
| 209 | return ToolResult(success=False, content="", error=str(e)) |
| 210 | |
| 211 | |
| 212 | class EditTool(Tool): |
no outgoing calls