EN ▾

Text to Image AI Prompt Enhancer Built on an LLM API

A text to image ai prompt enhancer takes a rough prompt like "old fisherman, harbor" and returns a richer one that an image model can use. You can build one in under 80 lines with an OpenAI-compatible LLM API. This tutorial gives the full script, three enhancement modes and a batch runner.

Updated:

Hand-cranked machine turning a plain sketch card into a richly detailed luminous tile
Isometric illustration of a request flowing through a pipeline of token blocks to a language model

Design: one function, three modes

Keep the core small. A single function takes a prompt and a mode, sends one chat completion, and returns a string. The modes differ only in the system message.

  • rewrite: fix grammar and ordering, keep every detail the user gave, add nothing.
  • enrich: keep the subject, add setting, lighting, lens or medium, and mood.
  • restyle: keep the subject and composition, change the visual style to one you pass in.

Separate modes matter because users want different things. Someone who typed a careful prompt does not want it rewritten into something else, while someone who typed three words wants a lot added. A mode flag lets one tool serve both.

The service behind the code is a text-only, OpenAI-compatible API with one open-weight model from an independent provider. It writes prompts; a separate image model renders them. If you are new to calling an API from Python, start with the LLM API tutorial.

The enhancer script

Install the client with pip install openai, put your key in the API_KEY environment variable, and save this as enhance.py.

import os, sys, json
from openai import OpenAI

client = OpenAI(base_url="https://api.uncensoredimagegenerator.com/v1",
                api_key=os.environ["API_KEY"])

MODES = {
    "rewrite": "Rewrite the image prompt for clarity: fix wording and order, "
               "keep every detail, add nothing new.",
    "enrich": "Expand the image prompt to 40 to 60 words. Keep the subject, add "
              "setting, lighting, camera or medium, and mood.",
    "restyle": "Keep the subject and composition of the image prompt but change "
               "the visual style to: {style}.",
}

def enhance(prompt, mode="enrich", style="film still"):
    system = MODES[mode].format(style=style) + (
        " Return JSON with keys 'prompt' and 'negative' (up to 10 short phrases)."
    )
    r = client.chat.completions.create(
        model="uncensored",
        messages=[{"role": "system", "content": system},
                  {"role": "user", "content": prompt}],
        response_format={"type": "json_object"},
        temperature=0.7,
        max_tokens=400,
    )
    return json.loads(r.choices[0].message.content)

if __name__ == "__main__":
    mode = sys.argv[1]
    print(json.dumps(enhance(" ".join(sys.argv[2:]), mode), indent=2))

Run python enhance.py enrich old fisherman, harbor and you get a JSON object with a longer prompt and a negative prompt. The trial key from the API key page is enough to try it.

Prompts for each mode, and why they work

Small wording choices in the system message change the output a lot.

Give limits as well as goals

"Expand the prompt" produces essays. "Expand to 40 to 60 words" produces something an image model can read. Numeric limits also keep you under the 77-token chunk size of SDXL-style text encoders.

Say what to keep

In rewrite and restyle mode, the risk is that the model changes the subject. State it directly: keep the subject, keep the composition. Where a name or a rare word must survive, tell the model to copy it unchanged.

Use examples sparingly

One example pair, an input and the output you wanted, steers style better than a list of adjectives. More than three examples start to make every result look alike.

Because the model is tuned to answer without content refusals for lawful adult use, you do not need workaround phrasing for dark or mature fiction themes. Anything involving minors in a sexual context is outside what the service will produce.

Batch processing a CSV

Add this to the same file to process a CSV with a prompt column. It runs several requests at once and retries when the API says to slow down.

import csv, time
from concurrent.futures import ThreadPoolExecutor
from openai import RateLimitError

def safe(row, mode="enrich"):
    for attempt in range(5):
        try:
            out = enhance(row["prompt"], mode)
            return {**row, "enhanced": out["prompt"], "negative": out["negative"]}
        except RateLimitError:
            time.sleep(5 * (attempt + 1))
        except (ValueError, KeyError):
            break
    return {**row, "enhanced": "", "negative": ""}

def run(src, dst, mode="enrich", workers=6):
    rows = list(csv.DictReader(open(src, newline="")))
    with ThreadPoolExecutor(max_workers=workers) as pool:
        done = list(pool.map(lambda r: safe(r, mode), rows))
    with open(dst, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(done[0].keys()))
        w.writeheader()
        w.writerows(done)

run("ideas.csv", "enhanced.csv")

Set workers to 8 at most on a full key and to 2 on a trial key. A limit hit comes back as HTTP 429 with the code rate_limited or concurrency, and temporary overload adds a Retry-After: 5 header. The loop above waits and tries again. Rows that still fail are written with empty fields, so you can filter and rerun only those. Failed requests are not billed.

Cost of a big batch

At $0.15 per 1M input and $0.50 per 1M output tokens, enhancing 5,000 prompts is cheap. Assume 150 tokens in (system message plus a short prompt) and 200 tokens out.

  • Input: 5,000 × 150 = 750,000 tokens × $0.15 / 1M = $0.1125.
  • Output: 5,000 × 200 = 1,000,000 tokens × $0.50 / 1M = $0.50.
  • Total: $0.6125, about 12 cents per thousand.

The output side dominates, so asking for shorter prompts is the lever that cuts cost most. Credit is prepaid and does not expire. Top-ups are any whole amount from $20 to $500 in crypto (USDT on TRC20 or USDC on Base), with +5% from $50, +10% from $100 and +15% from $200. See the pricing page.

Troubleshooting

When results look off, check these first.

  • Output ignores the mode. The user prompt contains instructions that fight the system message. Wrap the input in a label such as "Image prompt: ..." so the model treats it as material, not a command.
  • JSON parse errors. A reply cut at max_tokens ends mid-object. Raise the cap, or retry once.
  • Every result starts the same way. Raise temperature to 0.9 and add a small frequency_penalty such as 0.3.
  • Slow batches. Count your workers. With 2 on a trial key the run is slower than on a full key by design.
  • Key errors. A 401 means the key is missing or mistyped. Confirm the environment variable is set in the shell that runs the script.

For anything unexplained, quote the X-Request-Id response header when you contact support.

Ideas for extending it

Once the basic enhancer runs, a few additions make it more useful:

  • Judge the output. Send each enhanced prompt to a second call that checks it against a rule list. The page on LLM-as-a-judge in Python shows a working pattern.
  • Cache results. Hash the input and mode, and skip calls you already made. This saves money on repeated ideas.
  • Add a style library. Keep a JSON file of named styles and pass them into restyle mode.
  • Wire it to your image tool. Post the enhanced prompt and negative prompt to the HTTP API of ComfyUI or Automatic1111 and save the images beside the CSV.

The full parameter list, including streaming and balance checks, is in the API documentation.

Questions and answers

Does the API create the images?

No. It is a text-only service. It rewrites and expands prompts, and you send the result to an image model.

How long should an enhanced prompt be?

About 40 to 60 words suits SDXL-style encoders that read 77-token chunks. Longer prompts may be truncated by your UI.

How many prompts can I process at once?

A full key allows 8 concurrent requests and 300 per minute. A trial key allows 2 and 60. Retry on HTTP 429.

What does 5,000 prompts cost?

About $0.61 when each call uses roughly 150 input and 200 output tokens, at $0.15 and $0.50 per 1M tokens.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key
Get API key