Generating and previewing single-file web tools from a prompt

One of the most enjoyable features in modern chat apps is the ability to ask for a small web app, a habit tracker, a calculator, a chart or a simple game, and see it running beside the conversation within seconds. Lists of prompts for these mini apps circulate widely, and many people who are not programmers use them to build tools for their own work.
This article explains what is happening under the hood and how to build a similar loop with any chat API. You will see how to prompt for a self-contained HTML file, how to run it safely in a sandboxed frame, what quality to expect from different model sizes, and where the vendor's own app still has the advantage. The examples use the keyless OpenAI-compatible endpoint on this site.
Frequently asked questions
What is an artifact in a chat app?
It is a piece of generated content, often code, a document or a diagram, that the app shows in a separate panel instead of inline in the chat. For web code, the app renders it so you can interact with the result directly.
Is there anything special about the model behind artifacts?
The model writes code like any other answer. The special part is the app: it detects the code, runs it in a sandbox, and lets you iterate. You can build that layer yourself around any capable model.
How does a single-file app differ from a normal project?
A single-file app puts HTML, CSS and JavaScript into one document with no build step and no server. It is ideal for small tools and prototypes and easy to generate, but it does not scale to large applications.
Is it safe to run code a model generated?
Only inside a sandbox. A sandboxed iframe without same-origin access cannot read your page's cookies or storage. Never inject generated code directly into a page that has access to sensitive data.
Which is better for mini apps: a top commercial model or a mid-sized open one?
For anything with non-trivial logic, the top commercial models produce working code more often and handle follow-up changes better. A mid-sized open model can build simple tools and is fine for experimenting, but expect more fixes.
Can generated apps save data?
Within a sandbox, storage is usually restricted. You can let the parent page provide storage through messages, or allow the app to download and upload files. Vendor apps may offer built-in persistence features that a plain API does not.
Can I use external libraries in a generated app?
Yes, by loading them from a public CDN with a script tag. Ask the model to pin exact versions so the app does not break when a library updates.
Why does the app break after a few edits?
Each edit is a fresh generation, and models sometimes drop parts of the file or reintroduce old bugs. Keeping the full current file in the request and asking for the complete updated file reduces this.
What makes the experience work
The appeal of artifact-style features is the short loop: describe, see, adjust. The model writes a complete web page, the app renders it immediately, and you ask for changes in plain language. There is no editor, no build tool and no deployment. For many everyday tools, that is enough.
Three ingredients make it work: a prompt that reliably produces a self-contained file, a safe place to run that file, and a way to send the current version back with each change request. All three can be reproduced with a chat API and a small web page of your own.
Self-contained output
Everything the app needs lives in one HTML document. That makes extraction trivial and removes the need for a server.
Instant preview
Rendering the file the moment it arrives keeps the conversation focused on results, not on code.
Prompting for a single HTML file
Models will happily produce multi-file projects, framework scaffolding and installation instructions unless told otherwise. A clear system prompt fixes this: ask for exactly one HTML document with inline CSS and JavaScript, no external files except pinned CDN libraries, and no commentary outside the code block.
Being specific about constraints also improves quality. Mention that the app must work on a phone screen, must not use browser alerts, and should keep its state in memory. The more the model knows about the environment, the fewer surprises when it runs.
Ask for complete files
When iterating, request the whole updated file rather than a diff. Small models in particular apply partial edits unreliably in this setting.
Name the constraints of the sandbox
If storage or pop-ups are blocked in your frame, say so. The model will then avoid features that silently fail.
- Return exactly one complete HTML document, nothing else.
- Inline all CSS and JavaScript.
- Load libraries only from a CDN, with exact versions.
- Work in a sandboxed frame without network access to other sites.
- Fit a narrow phone screen without horizontal scrolling.

Generating and extracting the code
The script below asks the keyless endpoint for a small tool and saves the HTML to a file. It extracts the document from a fenced code block if the model adds one, which is common even when told not to. You can open the result in a browser or feed it into the preview page described next.
With the free endpoint, answers can be up to 16,000 tokens, which is plenty for small apps. Keep requests to one at a time per second, since the limit is one request per second per IP with bursts of three.
Always send the current version
The API is stateless. For each change, include the latest file in the request, never an older copy. The same rule prevents lost edits in coding tools, as explained in why assistants undo manual edits.
import re
from openai import OpenAI
client = OpenAI(base_url="https://api.apiclaudekeyfree.com/v1", api_key="none")
SYSTEM = ("Return exactly one complete HTML document with inline CSS and JavaScript. "
"No explanations. It must work offline in a sandboxed iframe and fit a phone screen.")
def make_app(request, current=None):
user = request if current is None else (
"Here is the current file:\n" + current + "\n\nChange request: " + request +
"\nReturn the full updated file.")
r = client.chat.completions.create(model="free-ai", max_tokens=6000,
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": user}])
out = r.choices[0].message.content
m = re.search(r"```(?:html)?\s*(.*?)```", out, re.S)
return (m.group(1) if m else out).strip()
html = make_app("A tip calculator with bill amount, tip percent slider and split between people.")
open("app.html", "w").write(html)
html = make_app("Add a dark mode toggle.", current=html)
open("app.html", "w").write(html)Running generated code safely
Generated code should be treated like code from a stranger. It may contain bugs that loop forever, it may try to load resources from unexpected places, and in rare cases a prompt could be manipulated to produce something harmful. The standard defence in a browser is a sandboxed iframe that loads the HTML through the srcdoc attribute, with the allow-scripts permission but without allow-same-origin.
In that configuration the app can run JavaScript but cannot read the parent page's cookies, local storage or DOM. If the app needs to save data, the parent can offer a narrow message-based interface, for example accepting a JSON object and storing it on the app's behalf.
Keep the frame isolated
Do not add same-origin permission unless you fully trust the code. Combined with script permission, it lets the code escape the sandbox.
Set a content security policy
A restrictive policy in the generated document, or served around it, limits which external hosts it can contact.

Quality across model sizes
How well this works depends heavily on the model. The strongest commercial models, Claude's larger tiers among them, can produce surprisingly complete apps with clean layouts, sensible state handling and few bugs, and they handle many rounds of changes without losing track. That is a big part of why vendor apps feel magical for this use.
A mid-sized open model such as free-ai, an independent model of about 35B parameters, does well on simple tools: calculators, converters, timers, small forms and basic charts. On complex interactions, multi-view apps or tricky layout, it makes more mistakes and may need several correction rounds. This site is not affiliated with Anthropic, and free-ai is not a Claude model.
Start small
Ask for the simplest version of the tool first, then add features one at a time. Each step is easier for the model to get right.
Paste error messages back
If the app shows an error in the browser console, include the exact message in the next request. Models fix specific errors far more reliably than vague complaints.
Useful mini apps to try
The best candidates are tools that need no server and no shared data. They are useful to one person, run entirely in the browser and can be described in a sentence or two. Many people build these for their own work: a pricing calculator, a meeting cost timer, a flashcard drill or a small data visualiser for a pasted CSV.
Avoid asking for anything that needs secret keys, accounts or a backend. A single-file app cannot keep secrets, and any key embedded in it is visible to anyone who opens the file.
Keep data local
For anything personal, design the app to work with files the user loads and saves, so no data leaves the device.
- Unit and currency converters with fixed rates you supply.
- Habit or task trackers that export to a JSON file.
- Simple charts from pasted CSV data using a pinned chart library.
- Quiz and flashcard tools for studying.
- Text utilities such as case converters, word counters and diff viewers.

Adding a model inside the generated app
A natural next step is an app that calls a model itself, for example a writing helper or a translator. Because the free endpoint has open CORS and needs no key, a generated single-file app can call it directly from the browser with a plain fetch request. That avoids the problem of embedding secrets, which would be unsafe with a paid key.
Keep in mind that each user's browser becomes the source IP, so per-IP limits apply to each user separately. For responsive interfaces, streaming the answer helps a lot; see streaming vs full responses for the trade-offs.
Handle busy responses
The endpoint returns 429 when limits are hit and 503 when busy. Show a friendly message and retry after a few seconds rather than failing silently.
async function ask(question) {
const r = await fetch("https://api.apiclaudekeyfree.com/v1/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "free-ai",
max_tokens: 400,
messages: [{ role: "user", content: question }]
})
});
if (!r.ok) throw new Error("HTTP " + r.status);
const data = await r.json();
return data.choices[0].message.content;
}Where the vendor apps still win
Building your own loop gives you control, portability and the freedom to use any model, but it is honest to note what you lose. Vendor apps combine a strong model with a polished interface, version history, sharing, built-in storage options and tuned system prompts that have been tested on many kinds of requests. Recreating all of that takes real work.
For one-off personal tools, the vendor app is often the quickest route. For embedding mini-app generation in your own product, or for experimenting without a subscription, a plain API with a sandbox is the flexible option.
Polish takes effort
Error recovery, version history and smooth iteration are features in their own right. Budget time for them if you build your own preview tool.
Portability is the payoff
Your own loop works with any OpenAI-compatible backend, so you can switch models as better or cheaper ones appear.

Send a test request to the keyless, OpenAI-compatible endpoint on the home page and see how it fits your project.