EN ▾

Uncensored LLM API for developers

unfilteredstory.cc

Get API key

How to Make an AI Generated Story: A Python Walkthrough

Knowing how to make an ai generated story that holds together past page three starts with not asking for it in one piece. Generate an outline, then write chapter by chapter with a rolling summary. This walkthrough does it in Python.

Updated

Key points

  • One outline call, then one call per chapter, each seeing the outline and a summary.
  • Ask for structured JSON for the outline so your code can loop over chapters.
  • Keep the last chapter in full and older chapters as short summaries.
  • A ten-chapter story of about 10,000 words costs roughly a cent in API fees.
Ten chapter booklets joined by a glowing thread beside a quill, showing chapter by chapter story generation
Typewriter whose page becomes a glowing ribbon winding through floating books, representing long-form story writing

Why chapter by chapter works better

You can ask a model for a whole story in one reply, and for a short piece that is fine. For anything longer, quality drops. The ending rushes, names change, an injury heals itself. The model is not forgetting on purpose; a single long reply has no checkpoints where you or the code can correct course.

A chapter loop adds those checkpoints. Each chapter is a small job with clear inputs: the plan, what already happened and what this chapter must do. You can read, edit or regenerate one chapter without touching the rest. It also gives you cost control, because you see tokens and dollars per chapter.

The steps are: write a premise, generate an outline, loop over chapters with a summary, then run a final consistency pass. Code for each follows. You need an API key from the API key page; new accounts can claim a small trial credit that covers many test stories.

Step 1: premise and outline

Start with a premise of two or three sentences: who, where, what goes wrong, what the story is about underneath. Then ask for the outline as JSON, so the program can read it.

import json
from openai import OpenAI

client = OpenAI(base_url="https://api.unfilteredstory.cc/v1", api_key="YOUR_KEY")

PREMISE = ("A retired lighthouse keeper on a remote island finds a locked "
           "radio that broadcasts conversations from forty years ago. "
           "Theme: what we owe the people we failed.")

def ask(system, user, temperature=0.8, json_mode=False):
    kwargs = {"response_format": {"type": "json_object"}} if json_mode else {}
    r = client.chat.completions.create(
        model="uncensored",
        temperature=temperature,
        messages=[{"role": "system", "content": system}, {"role": "user", "content": user}],
        **kwargs,
    )
    return r.choices[0].message.content, r.usage

raw, usage = ask(
    "You plan novellas. Return JSON: {\"title\": str, \"characters\": [{\"name\": str, \"note\": str}], "
    "\"chapters\": [{\"n\": int, \"title\": str, \"beats\": str}]}. Exactly 10 chapters.",
    "Premise: " + PREMISE + "\nTone: quiet, uneasy, literary. Each chapter has a turn that changes something.",
    json_mode=True,
)
outline = json.loads(raw)
print(outline["title"], len(outline["chapters"]))

Read the outline yourself and edit the JSON. Fixing a weak chapter plan here costs nothing compared with fixing it after the prose exists.

Step 2: the chapter loop

For each chapter, send four things: story rules, the outline, a running summary of earlier chapters, and the full text of the previous chapter (so the prose style and last scene carry over).

RULES = ("You are a novelist. Write the requested chapter in third person, past tense. "
         "About 1000 words. Show, do not summarize. Keep names and facts consistent with "
         "the outline and the summary. End the chapter on a moment that pulls forward.")

chapters, summary = [], "Nothing has happened yet."
for ch in outline["chapters"]:
    prev = chapters[-1] if chapters else "(this is the first chapter)"
    user = (
        "Outline:\n" + json.dumps(outline) + "\n\n"
        "Summary of earlier chapters:\n" + summary + "\n\n"
        "Previous chapter, full text:\n" + prev + "\n\n"
        "Write chapter " + str(ch["n"]) + ": " + ch["title"] + ". Beats: " + ch["beats"]
    )
    text, usage = ask(RULES, user, temperature=0.85)
    chapters.append(text)
    summary, _ = ask(
        "Update the story summary in at most 250 words. Keep names, injuries, promises and open questions.",
        "Current summary:\n" + summary + "\n\nNew chapter:\n" + text,
        temperature=0.2,
    )
    print(ch["n"], usage.prompt_tokens, usage.completion_tokens)

open("story.txt", "w").write("\n\n".join(chapters))

One trick improves the prose a lot: add a voice sample. Paste 150 words of writing in the style you want (your own, or any text you have the rights to use) into the rules and say "match this voice, do not copy its content". Models follow a sample more closely than adjectives like "lyrical" or "spare". Add the sample to the system message so it stays constant across chapters, and the narrator's voice will not wander between chapter two and chapter eight.

The summary call uses a low temperature because it should be exact, not creative. Writing the story file after the loop is fine; for long runs, save each chapter as soon as it arrives, so a network error does not lose work.

Context trimming: what to keep as the story grows

The window is 100,000 tokens for prompt plus reply, about 70,000 words. A ten-chapter story fits entirely, so for short work you can paste every previous chapter instead of a summary. For a novel-length project you cannot, and even before the limit, cost and focus favor trimming.

  • Always keep: rules, outline, character list.
  • Keep in full: the previous chapter, since style and the last scene live there.
  • Keep as summary: everything older, in 250 words or fewer.
  • Pin separately: a "facts that must not change" list (eye colors, dates, who knows the secret).

When something drifts anyway, add the correct fact to the pinned list and regenerate only that chapter. The guide to the best AI to write unfiltered stories compares more approaches to long fiction.

Cost of a ten-chapter story

Rates are $0.15 per 1M input tokens and $0.50 per 1M output tokens. Estimate one chapter call: about 2,600 tokens in (outline, summary, previous chapter, instructions) and about 1,400 tokens out (roughly 1,000 words).

PartMathCost
Input per chapter2,600 / 1,000,000 x $0.15$0.00039
Output per chapter1,400 / 1,000,000 x $0.50$0.0007
One chapter$0.00109
Ten chapters10 x $0.00109$0.0109

The outline call and ten short summary calls add a fraction of a cent. The whole story lands near a cent and a half even with a couple of regenerated chapters. Failed or refused requests are not charged. The pricing page lists top-up amounts ($20 to $500, by crypto) and bonuses.

Step 3: the consistency pass and polish

After the loop, send the whole story back (about 14,000 tokens for ten chapters) and ask for a list, not a rewrite: contradictions, repeated images or phrases, and chapters where the turn is weak. Then fix those chapters with targeted prompts such as "Rewrite chapter 4 so the radio first speaks in the final scene, not the middle. Keep everything else."

Polish prompts that work well:

  • "List the five most repeated words or images across the story."
  • "Mark any line where a character knows something they could not know yet."
  • "Suggest three stronger last lines for chapter 7."

The model is tuned to answer without content refusals for lawful adult use, so dark themes in fiction do not get interrupted mid-chapter. Sexual content involving minors is never allowed. Read the output yourself before you publish anything; fluent text is not the same as finished writing.

Limits to plan around

If you run several stories in parallel, a small worker pool of four keeps you well inside the limits and finishes batches faster than a single loop. Give each worker its own story folder and its own summary file, so a crash in one does not affect the others. Log the token counts from every response; they let you check the cost table above against reality after the first run.

A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. The chapter loop is sequential, so you will not hit these, but a batch of many stories at once can. HTTP 429 with rate_limited means too many per minute; concurrency means too many at once. Wait and retry, and read the docs for the full parameter list. The service is text only, so covers and illustrations come from other tools.

Questions and answers

How long a story can I generate?

Chapter by chapter, as long as you like. Each call can use up to the 100,000-token window, and a rolling summary keeps earlier events in view.

Can I generate the whole story in one request?

Yes for short pieces, because max_tokens is optional and replies can use the rest of the window. Quality and control are better with an outline and separate chapters.

What temperature should I use for stories?

Around 0.8 to 0.9 for prose, and 0.2 for summaries or fact lists that need to stay exact.

How do I pay?

Prepaid credit, topped up with crypto. New users can also claim $0.50 of trial credit with no card.

Your key is one form away

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

Start with trial credit

Email and password, key on screen right away.