Skip to main content

Tellers Network Image Generation Tool (tlnw-generate-image)

tlnw-generate-image provides a Python image-generation library and CLI, plus an authenticated web API deployed as a Cloudflare Python Worker. The library and API share the asynchronous, in-memory generate_image() function, including model sizing, master prompts, output conversion, WebP copies, and thumbnails. The existing file-based CLI and tlnw_generate_image.core API remain available.

Provider adapters retain GPT Image, DALL-E, and Imagen model routing. Availability depends on the provider: OpenAI has retired DALL-E and GPT Image 1, and Google has shut down Imagen in the Gemini API. The default is gpt-image-2.6-sunburst across the library, CLI, and HTTP API. Explicit model selections are preserved. Legacy provider failures return an API error.

OpenAI generation uses the Images API directly: tlnw_generate_image/generation.py sends HTTP requests to /v1/images/generations or /v1/images/edits, while the file-based CLI provider in tlnw_generate_image/providers/gpt_image.py calls client.images.generate() or client.images.edit(). There is currently no mainline text model or Responses API integration. With the Responses API, a mainline model goes in the top-level model field and the image model goes in tools[].model for the image_generation tool.

Installation

pip install tlnw-generate-image

For the existing Google SDK-based file pipeline, install tlnw-generate-image[google].

Python library

Set OPENAI_API_KEY or GEMINI_API_KEY in your process environment, or pass api_key= explicitly. Generation raises ValueError, ConfigurationError, or ProviderError; it does not exit the process.

import asyncio
from pathlib import Path
from tlnw_generate_image import generate_image

async def main():
    result = await generate_image(
        "A fox reading beneath a tree",
        model="gpt-image-2.6-sunburst",
        master_prompt="Watercolor illustration.",
        orientation="landscape",
        quality="high",
        format="PNG",
        webp=True,
        thumbnail=True,
    )
    Path("fox.png").write_bytes(result.image.data)
    Path("fox-thumbnail.webp").write_bytes(result.thumbnail.data)

asyncio.run(main())

GenerationResult contains model, resolved size, normalized quality, image, and optional webp and thumbnail images. Each image has data (bytes), content_type, width, and height. result.to_dict() returns the same base64 JSON structure as the API. Reference images are passed as reference_images=[Path("reference.png").read_bytes()] for GPT Image models. These interfaces never read server-side paths or write files during generation; the caller chooses where to save results.

Features

  • Extensible OOP Provider Architecture: Clean separation of model providers (DalleProvider, GptImageProvider, GoogleImagenProvider) with registry-based dynamic routing.
  • Intelligent Size & Quality Preset Mapping: Standardizes orientation presets (landscape, portrait, square) and qualities, automatically converting them to provider-native formats: aspect ratios (e.g. "16:9") for Google Imagen, or concrete dimensions (e.g. "1792x1024") for OpenAI.
  • Custom Dimension Resolution & Validation: Automatically maps exact resolution values (e.g., 1920x1080 or 1536x1024.txt in file names) to the closest supported native aspect ratios when routing to Imagen. For gpt-image-2, it validates custom resolution constraints locally (divisibility by 16, aspect ratios between 1:3 and 3:1, and a maximum resolution edge of 3840px with a minimum edge of 2160px).
  • Auto-resolution of Output Sizing: Extracts target sizes from prompt filename trailing suffixes (e.g., -1536x1024.txt).
  • Prompt Composition: Concatenates local directory illustration-master-prompt.txt automatically with individual scene prompts.
  • Automatic WebP Conversion: Generates and optimizes WebP formats (featured.webp and thumbnail.webp with max-dimension constraints).
  • Standardized Output Filenames: Output filenames are derived from the prompt file base: <prefix>-prompt.txt or <prefix>-prompt-<size>.txt become <prefix>.<ext>.
  • Optional WEBP Copy: Use --webp to create an additional lossless <prefix>.webp copy alongside the main output.
  • Thumbnail Generation: Use --thumbnail to create <prefix>-thumbnail.webp resized to max 768px with 75% quality.
  • Dry Run: Use --dry-run to log planned file generation and conversions without API calls or file writes.
  • Recursive File Patterns: --file-pattern accepts glob patterns including ** for recursive discovery (e.g. --file-pattern "**/*-prompt-*.txt" root-folder).

Usage

Generate illustration for a story folder:

generate-image /path/to/story_folder --model dall-e-3 --webp --thumbnail

Process specific prompt files:

generate-image --file /path/to/prompt-1536x1024.txt --model imagen-4-ultra

Dry-run example (logs planned outputs without API calls or file writes):

generate-image /path/to/story_folder --dry-run --file-pattern "**/*-prompt-*.txt"

Authenticated web API

The Worker follows Cloudflare's Python Workers entrypoint and packaging model: Default(WorkerEntrypoint), the python_workers compatibility flag, and dependencies vendored by pywrangler sync. Outbound requests use native asynchronous workers.fetch; image conversion uses Pillow in memory. Cloudflare-specific imports stay in worker.py.

All endpoints require Authorization: Bearer <token>. Each environment has a different hardcoded API_BEARER_TOKEN under env.<environment>.vars in wrangler.jsonc, as the initial authentication mechanism. Read or rotate the token there; releases redact it from child-process output. This is a shared token for each environment, with no user database or token issuance endpoint. Missing authentication configuration fails closed.

POST /v1/images/generations accepts Content-Type: application/json:

curl https://<worker-url>/v1/images/generations \
  -H "Authorization: Bearer <token-from-selected-wrangler-environment>" \
  -H "Content-Type: application/json" \
  --data '{"prompt":"A fox reading beneath a tree","orientation":"landscape","webp":true,"thumbnail":true}'
JSON option Default / meaning
prompt Required nonempty text; combined prompt limit 32,000 characters
model gpt-image-2.6-sunburst; retains GPT Image, DALL-E, and Imagen routing
master_prompt Optional text prepended to prompt
orientation square, landscape, or portrait; default square
size Optional positive WIDTHxHEIGHT; Imagen also accepts a supported aspect ratio
quality low, medium, high, standard, hd, or auto; normalized per model
format PNG (default), JPEG, JPG, or WEBP
webp Boolean; add a lossless WebP copy
thumbnail Boolean; add a WebP thumbnail, maximum dimension 768 px, quality 75
reference_images Up to four raw base64 PNG/JPEG/WebP strings for GPT Image edits; no paths, URLs, or data-URL prefixes

The response contains model, size, quality, and image: {b64_json, content_type, width, height}. Optional webp and thumbnail fields have the same image structure. Decode b64_json to obtain image bytes. Requests return the completed result; no files or job results are persisted.

GET /health returns {"status":"ok"} with valid authentication. It verifies API reachability, not provider credentials or model access.

Errors use {"error":"..."}: 400 invalid JSON/options, 401 invalid bearer token, 404 unknown route, 405 wrong method, 413 body over 8 MiB, 415 wrong content type, 503 missing API/provider configuration, and 502 provider/network/image failures. Provider response bodies and keys are never returned. Responses use Cache-Control: no-store; 401 includes WWW-Authenticate: Bearer. Encoded provider images are limited to 20 MiB and 16 megapixels. Browser CORS access is not enabled; use a server-side client or same-origin proxy.

Development and checks

Prerequisites: Python 3.12+ for tooling (the library still supports Python 3.10+), Node.js 22+, and uv. The configured compatibility date selects the Python Workers runtime independently of the host Python version. From a fresh checkout:

npm ci
uv sync --locked --group workers
uv run --locked pytest -q
npm test

uv.lock pins host/tool dependencies. workers/pyproject.toml declares the minimal Worker dependencies (Pillow; the CLI supplies the runtime SDK), and workers/pylock.toml pins their Pyodide builds. Provider SDKs remain available to the file-based library/CLI and are imported lazily, so they are not needed in the Worker. To intentionally refresh the Worker lock after changing dependencies or compatibility settings, run npm run lock:worker, then review and commit workers/pylock.toml. Keep uv.lock current with uv lock when editing the root pyproject.toml.

For local development, put provider credentials in the ignored .dev.vars.staging (or .dev.vars.production):

OPENAI_API_KEY=<provider-key>

Then run npm run dev -- --env staging. This builds an isolated snapshot and starts Wrangler locally at http://localhost:8787. Authenticate using the staging bearer token from wrangler.jsonc. Only the selected .dev.vars.<environment> is copied into the development snapshot. Restart this command after source changes; the isolated snapshot does not watch the original sources. The local server holds the release lock until stopped.

Cloudflare release procedure

Select staging or production explicitly; neither is a default. Set CLOUDFLARE_ACCOUNT_ID or supply --account-id <32-character-account-id>. An account pinned in configuration cannot be overridden with a conflicting CLI account. Authenticate Wrangler using CLOUDFLARE_API_TOKEN (CI) or the local Wrangler login flow. Target Workers are tlnw-generate-image-staging and tlnw-generate-image-production on workers.dev unless you configure environment-specific routes.

Before the first real release, the cloud operator must install at least one provider secret for the selected Worker, using the pinned local Wrangler. For example, after setting the account and Wrangler authentication:

node node_modules/wrangler/bin/wrangler.js secret put OPENAI_API_KEY --config wrangler.jsonc --env staging
# Optional alternative provider:
node node_modules/wrangler/bin/wrangler.js secret put GEMINI_API_KEY --config wrangler.jsonc --env staging

Use --env production for production setup. Wrangler may offer to create the named Worker when installing its first secret. Provider keys are separate from the hardcoded API bearer token. A request for a provider whose key is absent returns 503.

These commands are alternatives, each targeting one environment:

npm run release -- --env staging --account-id <account-id>
npm run release -- --env production --account-id <account-id>

Each real release:

  1. Validates source target, account, distinct Worker names and bearer tokens. Acquires an exclusive .release.lock and creates a fresh .release/<environment>/build-* snapshot.
  2. Verifies authentication/Worker readiness by listing remote secret names; requires OPENAI_API_KEY and/or GEMINI_API_KEY. It never reads secret values or installs secrets.
  3. Copies shared Python source under the snapshot's src/ directory, flattens the selected Wrangler environment with src/worker.py as its entrypoint, and vendors dependencies from the Worker manifest/lock using the pinned local Python Workers CLI. Build virtual environments stay outside module discovery. Dependency resolution must preserve the committed Pyodide lock.
  4. Validates the new target and dependency output, hashes the snapshot, and runs pinned Wrangler deploy --dry-run against it.
  5. Rechecks source and deployment files, then deploys the same validated snapshot. Flattened configs receive no second --env; inherited selectors are cleared and the account is pinned in both config and child environment.

The command stops at the first failure, reports its stage and preserves the child exit code. It releases only its own lock. A preexisting lock blocks a release; it is never deleted automatically. Do not edit inputs or run other builds during release. Snapshots are retained locally for inspection and ignored by Git; they contain the configured bearer token. On deployment failure the remote outcome may be uncertain: inspect the selected Worker before retrying. No automated rollback occurs. The command performs no migrations, resource provisioning, secret installation, or PyPI publication.

Mode Actions
--dry-run Source preflight and activity printout only; no subprocess, lock, build, or network
--check Fresh build, target validation, and Wrangler bundle dry-run; no remote secret listing or deployment
no mode flag Remote preflight, fresh build, validation, bundle check, and live deployment

The modes are mutually exclusive. --check verifies local bundling, not cloud credentials, provider access, or successful image generation. A local check can use a synthetic account ID:

npm run release -- --env staging --account-id 00000000000000000000000000000000 --dry-run
npm run release -- --env staging --account-id 00000000000000000000000000000000 --check

For review, developers run the Python/Node tests and optional local bundle check above; no UI check, migration, secret setup, or deployment is required. After an authorized live deployment, the cloud operator checks GET /health with the selected token (expect 200), repeats without a token (expect 401), then optionally sends the generation request above with a provider key/model available to that environment (expect base64 image output; this incurs provider usage).

Metadata

Release files for tlnw-generate-image 0.8.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tlnw-generate-image 0.8.0
File Size Uploaded Provenance Actions
tlnw_generate_image-0.8.0.tar.gz 33.1 kB With provenance Details for tlnw_generate_image-0.8.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for tlnw-generate-image 0.8.0
File Interpreter ABI Platform Actions
tlnw_generate_image-0.8.0-py3-none-any.whl Python 3 none any Details for tlnw_generate_image-0.8.0-py3-none-any.whl

Total release size: 59.6 kB

Release files / tlnw_generate_image-0.8.0.tar.gz

Download URL tlnw_generate_image-0.8.0.tar.gz
Size 33.1 kB
Tags Source
SHA-256 checksum
How to use checksums
1b7398f1ccb86d89625c016dca04be3744fdfc6e7b61939b718e3b28e7928b78
BLAKE2b-256 checksum
How to use checksums
a1b52c982e275e7830473545f4bff78d6e4d33076aa7fc05b8d0bc7c6b2c4deb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Release files / tlnw_generate_image-0.8.0-py3-none-any.whl

Download URL tlnw_generate_image-0.8.0-py3-none-any.whl
Size 26.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ee51a8228a2e4b015096908f256f9264185452dc9e4eb3702163182ebabd6652
BLAKE2b-256 checksum
How to use checksums
07ee13b9ef4fe6bb468741deb75125b99afd2947424ca43a614bfb66a4f4fff9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Security for tlnw-generate-image 0.8.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for tlnw_generate_image-0.8.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page