Rename files with AI

If you have a messy folder of files, like I do, wouldn't it be great if an AI agent can help to sort and rename them accordingly?

Scenario

Filesystem Operation Flowchart

For this demo, we will show how to rename files in a folder with the help of an LLM.

The AI agent will list the files in the folder, read the content of the files, and then rename them accordingly.

I have a test folder with a doc.md file. It contains an itinerary for Perth. I'm too lazy to rename it myself, so I'll ask the AI agent to help me.

# 5-Day Itinerary for Perth, Australia

1. **Day 1**: Visit Kings Park and Botanic Garden
2. **Day 2**: Explore Fremantle and its markets
3. **Day 3**: Take a day trip to Rottnest Island
4. **Day 4**: Visit Perth Zoo and Elizabeth Quay
5. **Day 5**: Enjoy Swan Valley wine tasting tour

This itinerary offers a perfect blend of nature, culture, and leisure activities, showcasing the best of Perth and its surroundings.

To complete this tasks, our AI agent is equipped with our filesystem operation tools, which enable it to:

  • Read files
  • Create files
  • Edit files
  • Create directories
  • List the children of a directory
  • Move files and directories
  • Find files and directories
  • And more

Note: The tool to read files can currently only read plaintext files, code files, and markdown files but not documents, media files, or binary files.

Setup

To get started, we first set the following environment variables in a .env file:

  • ALLOWED_DIR: The directory that we allow the AI agent to access (e.g. /Users/username/Documents/folder)
  • <COMPANY>_API_KEY: The API key of the model you want to use

Now, we are ready to load the filesystem tool index and build our AI agent.

Scripts

Here are the scripts for the various major LLM providers and frameworks. Remember to install the required dependencies mentioned at the top of each script.

import os
import anthropic
from dotenv import load_dotenv
import stores

# Load environment variables
load_dotenv()

# Load tools and set the required environment variables
index = stores.Index(
    ["silanthro/filesystem"],
    env_var={
        "silanthro/filesystem": {
            "ALLOWED_DIR": os.environ["ALLOWED_DIR"],
        },
    },
)

# Initialize Anthropic client and messages
client = anthropic.Anthropic()
messages = [
    {
        "role": "user",
        "content": "Rename the files in the '/Users/username/Documents/folder' directory according to their content",
    }
]

# Define agent loop
def run_agent_loop():
    while True:
        # Get response from the model
        response = client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=1024,
            messages=messages,
            # Pass tools
            tools=index.format_tools("anthropic"),
        )

        # Check if all blocks contain only text, which indicates task completion for this example
        blocks = response.content
        if all(block.type == "text" for block in blocks):
            print(f"Assistant response: {blocks[0].text}\n")
            return  # End the agent loop

        # Otherwise, process the response, which could include both text and tool use
        for block in blocks:
            if block.type == "text" and block.text:
                print(f"Assistant response: {block.text}\n")
                messages.append({"role": "assistant", "content": block.text})
            elif block.type == "tool_use":
                name = block.name
                args = block.input

                # Execute tool call
                print(f"Executing tool call: {name}({args})\n")
                output = index.execute(name, args)
                print(f"Tool output: {output}\n")
                messages.append(
                    {
                        "role": "assistant",
                        "content": [
                            {
                                "type": "tool_use",
                                "id": block.id,
                                "name": block.name,
                                "input": block.input,
                            }
                        ],
                    }
                )
                messages.append(
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "tool_result",
                                "tool_use_id": block.id,
                                "content": str(output),
                            }
                        ],
                    }
                )


# Run the agent loop
run_agent_loop()

In the folder where you have this script, you can run the AI agent with the command:

python rename-files.py

The AI agent will repeatedly access, read, and rename files in the entire folder.

If you have any questions, let us know on GitHub.