Skip to main content

Generating Websites

To generate websites and other multi-file applications, we will first prompt the LLM to split the code into multiple files and then make use of h9.save() to store multiple files.

LLMs with Files

Most LLM generate code blocks by default, not files. We can change this behavior using a system prompt to request the LLM to generate code files, defined as code blocks with an additional file name.

Your replies can include markdown code blocks but they must include a
filename parameter after the language. For example,

```javascript filename=code.js
```

The main html file must ne named index.html. You can generate other web files
like javascript, css, svg that are referenced from index.html

Storing Files

YOu can make use of h9.extract() to extract the file blocks generated by the LLM, followed by h9.save() with the dictionary of text file names to content to store.

import hal9 as h9
import openai
import os

files = h9.extract("""
```javascript filename=code.js
function go() {
document.getElementById('msg').innerText = Math.random();
}
```

```html filename=index.html
<html>
<head>
<script src="code.js"></script>
</head>
<body>
<button onclick="go()">Go!</button><div id="msg"></div>
</body>
</html>
```
""", default={})

h9.save("index.html", files=files)

If you prefer to save the files without h9.save(), you can save them under a subfolder under ./storage. In order to render this folder correctly, use an appropriate extension; for example, html for a website:

base_path = './.storage/website.index.html/'
os.makedirs(base_path, exist_ok=True)

for filename, content in files.items():
file_path = os.path.join(base_path, filename)
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)