picogent-py/picogent/tools/write.py
Markov 5417980b76 Initial implementation of PicoGent - minimal AI coding agent
- Implemented ReAct loop in agent.py
- Added Anthropic provider using httpx (no SDK)
- Created tools: read, write, edit, bash
- Added session management with JSONL format
- Included configuration system with env var support
- Added CLI interface and example usage
- Minimal dependencies: only httpx
2026-02-22 23:18:02 +01:00

62 lines
2.1 KiB
Python

"""
Write file tool
"""
import os
from typing import Dict, Any
from .registry import Tool
class WriteTool(Tool):
"""Tool for writing files with automatic directory creation"""
def __init__(self):
super().__init__(
name="write",
description="Write content to a file. Creates parent directories if they don't exist. Overwrites existing files.",
parameters={
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to the file to write (relative or absolute)"
},
"content": {
"type": "string",
"description": "Content to write to the file"
}
},
"required": ["file_path", "content"]
}
)
async def execute(self, args: Dict[str, Any]) -> str:
"""Execute the write tool"""
file_path = args.get("file_path")
content = args.get("content", "")
if not file_path:
return "Error: file_path is required"
try:
# Convert to absolute path if relative
if not os.path.isabs(file_path):
file_path = os.path.abspath(file_path)
# Create parent directories if they don't exist
parent_dir = os.path.dirname(file_path)
if parent_dir and not os.path.exists(parent_dir):
os.makedirs(parent_dir, exist_ok=True)
# Write the file
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
# Get file info
file_size = os.path.getsize(file_path)
line_count = content.count('\n') + (1 if content and not content.endswith('\n') else 0)
return f"Successfully wrote {file_size} bytes ({line_count} lines) to '{file_path}'"
except Exception as e:
return f"Error: Could not write file '{file_path}': {e}"