DEV Community

SupermanSpace
SupermanSpace

Posted on

4 1 1 1

Create Folder Structure using LLM

I wanted to share an update on a project I worked on some time ago. I've made some changes to the code for creating project structures using LLM. Here’s the code:

import json
import os
import cohere

# Initialize the Cohere client with a more secure approach
co = cohere.Client(api_key='YOUR_COHERE_KEY')

def create_project_structure(structure, base_path="/content/"):
    """
    Create a directory and file structure based on a nested dictionary.
    """
    try:
        for folder, files in structure.items():
            folder_path = os.path.join(base_path, folder)
            os.makedirs(folder_path, exist_ok=True)
            for file_name, content in files.items():
                file_path = os.path.join(folder_path, file_name)
                if isinstance(content, dict):
                    create_project_structure(content, base_path=folder_path)
                else:
                    with open(file_path, "w") as file:
                        file.write(content)
        return "Project structure created successfully."
    except Exception as e:
        return f"An error occurred: {str(e)}"

# JSON schema for the function argument
tools = [{
    "name": "create_project_structure",
    "description": "Create an entire project structure with specified files and contents.",
    "parameter_definitions": {
        "structure": {
            "description": "Dictionary specifying folders and files with their contents.",
            "type": "dict",
            "required": True
        },
        "base_path": {
            "description": "Base path where the project structure will be created.",
            "type": "str",
            "required": False
        }
    }
}]

functions_map = {
    'create_project_structure': create_project_structure
}

# Placeholder for example user request and handling
message = "write complete flappy bird game using unity"
preamble = """
## Task & Context
Answer questions and handle requests on a variety of topics using appropriate tools and research methods.

## Style Guide
Respond in full sentences, using proper grammar and spelling, unless requested otherwise.
"""

# Simulate handling a user request
response = co.chat(
    message=message,
    tools=tools,
    preamble=preamble,
    model="command-r",
    force_single_step=True
)

# Process and execute the recommended tool calls
tool_results = []
for tool_call in response.tool_calls:
    output = functions_map[tool_call.name](**tool_call.parameters)
    tool_result = {
        "name": tool_call.name,
        "parameters": tool_call.parameters,
        "outputs": [output],
        "call": tool_call
    }
    tool_results.append(tool_result)

print("\nTool execution results:\n")
print(json.dumps(tool_results, indent=4))

# Handle the final response using the results from tool calls
final_response = co.chat(
    message=message,
    tools=tools,
    tool_results=tool_results,
    preamble=preamble,
    model="command-r",
    temperature=0.3,
    force_single_step=True
)

print("Final answer:")
print(final_response.text)
Enter fullscreen mode Exit fullscreen mode

Tweak it for your needs and best of luck 🤞

If you'd like to support my work, consider checking out my Patreon: Superman Space.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay