AI Recipe Image Generation
Audience: User, Org Admin, System Admin, Developer Related: Providers And Connections · Seeds And Usage · Editing And Cache · Data Retention
Blackcap can generate recipe images through configured AI providers and quality profiles. Generation uses a registered AI use case, validates the provider response, reserves and commits AI Seeds through the usage system, stores generated assets according to retention policy, and associates accepted output with the recipe.
Provider availability, quality levels, cost, monthly allotments, and asset retention are administrative concerns. Generated images should be clearly treated as generated content rather than source photography.
Image generation architecture
Scope
The shared image-generation foundation uses manual_recipe_image_generation for manual Recipe images, image review for new AI-created Recipes, optional Plan Meals-created Recipe images, and supported whole-Meal images. Each entry point applies its own review/confirmation and Seed-budget rules. This is not a separate Create Image database migration or a second independent image provider adapter.
Existing seams used
- Flask Blueprint routes remain outside
inky_admin_app.py. - All durable AI data access is isolated in
inky_admin/repositories/ai_repository.pyand uses the centralized application database service. - Recipe authorization continues to use
recipe_user_can_manageand existing recipe permissions. - Accepted generated images enter the same optimized recipe preview, metadata, thumbnail, and cache-build paths used by uploaded images.
- Provider credentials use Blackcap's encrypted secret helper and are never returned after save.
- Durable AI job rows are executed by the existing Blackcap/Gunicorn application processes. Expiring database leases coordinate ownership and restart recovery; no separate AI worker/systemd service is used.
Component flow
Recipe Library / Recipe Editor
-> AI Blueprint
-> AI Image Service
-> AI Configuration Service
-> AI Seed Service
-> AI Repository
-> centralized database transaction / adapter
-> AI Job Service
-> AI Provider Registry
-> OpenAI Adapter OR Gemini Adapter
-> Generated Image Artifact Service
-> AI Seed settlement/release
-> AI usage event
-> pending recipe-form image selection
-> existing recipe save + cache services when the page is saved
Provider contract
Provider adapters expose:
validate_connection(connection, profile)generate_image(request, on_submitted=...)retrieve_image(request, provider_response_id)when the provider supports durable retrieval- normalized success data containing image bytes, MIME type, safe provider request ID, durable provider response ID, latency, model, and normalized provider usage
- normalized failures: authentication, rate limit, safety rejection, timeout/unknown outcome, invalid response, unsupported configuration, terminal provider response, retryable provider failure, and permanent provider failure
Recipe routes do not construct provider-specific payloads.
Durable OpenAI requests and retry
OpenAI image generation uses the Responses API with the image_generation tool, background=True, and store=True.
- Blackcap assigns every attempt its own
aijob_*ID and sends that value asX-Client-Request-Idfor tracing. - OpenAI returns a durable
resp_*response ID. Blackcap stores it on the AI job immediately through the provider submission callback. X-Client-Request-Idis not treated as a retrieval key. Recovery always uses the storedresp_*ID.- The OpenAI SDK is configured with automatic retries disabled so Blackcap is the only retry authority.
- After a process restart, active jobs with a stored provider response ID resume by retrieving the existing response rather than submitting another paid request.
- When a request ends with an uncertain provider outcome, Blackcap marks the durable provider interaction/job
outcome_unknown, keeps the provider evidence for cost reconciliation, and releases the user's AI Seed reservation because no valid image response was received. It does not assume the original provider operation is safe to resubmit. - For a retrievable provider operation, recovery checks the saved provider ID before any new provider submission. An
outcome_unknownoperation requires an explicit user retry; that retry creates its own newly approved AI Seed reservation. - A successful recovery settles the original durable reservation idempotently and returns the recovered generated image.
- Blackcap does not treat
provider_recovery_unsupportedor an otherwise unknowable provider outcome as permission for another paid request. A new request is a distinct explicit retry. - If the original submission failed before Blackcap received a
resp_*ID, provider-side retrieval is impossible; the job still records its Blackcap client request ID for reconciliation, and Retry may submit one new request.
AI Seed accounting
The model uses accounts, buckets, an append-only ledger, reservations, and usage events.
- Organization and user accounts are independent.
- User accounts are global across organizations.
- Monthly organization buckets use half-open billing periods and expire at the next period boundary.
- The original billing anchor is retained when a short month clamps a boundary.
- Organization spending consumes the current monthly bucket first, then other expiring buckets, then non-expiring buckets.
- A request reserves AI Seeds before provider submission. Confirmed provider completion settles once; failures known to occur before chargeable provider work may release once; uncertain provider outcomes keep the reservation for reconciliation.
- Retry always has a separate reservation and usage event. It consumes that reservation only when recovery or a newly submitted request produces a valid image.
- The Default organization uses an unlimited organization policy rather than a fabricated balance. A System Admin’s personal source is unlimited, but organization funding still evaluates the selected organization’s actual policy and balance. Usage records the configured AI Seed amount that would have been consumed for unlimited sources.
- Provider token usage is stored independently from the configured AI Seed price.
- Once a validated image exists, a deleted recipe or later internal failure moves the job to recoverable reconciliation; it does not release the charge or submit another provider request.
Profile mapping
The user sees provider-independent quality profiles. A System Admin maps each profile to a provider connection, model, output size, quality, format, aspect ratio, and allowlisted options. Profile keys remain stable while display names, prices, provider mapping, and order can be edited.
Manual recipe drafts
A manually created recipe may generate an image before the recipe row exists.
- The browser creates an
aidraft_*identifier for the current manual-recipe form. - Before generation, both browser and server require recipe name, description, at least one ingredient, and at least one instruction/step.
- The normalized draft recipe is snapshotted into the AI job and used to build the provider prompt.
- The generated candidate remains associated with the current user, organization, and draft identifier.
- Selecting Use This Image places the candidate ID into the unsaved recipe form; it does not create a recipe or start cache generation.
- When the recipe is saved, Blackcap transactionally reassigns the draft job and candidate to the new recipe ID, promotes the selected image, and queues the normal recipe cache build once.
The metadata editor and editable-content pages use the same pending-selection behavior for existing recipes.
Image lifecycle
- Validate the saved recipe or complete manual-recipe draft.
- Reserve the selected source's AI Seeds.
- Snapshot profile, cost, provider connection, model, output settings, prompt version, billing identity, and retry lineage.
- Generate asynchronously through the configured provider.
- For OpenAI, store the durable Responses API ID before polling for completion.
- Validate signature, MIME type, dimensions, decoded size, and image readability.
- Settle AI Seeds and keep a review candidate for the configured retention period.
- Selecting the candidate updates only the current edit form and marks it unsaved.
- Saving the recipe promotes the candidate through the existing recipe preview path, invalidates image derivatives and browser/session caches, and queues one normal cache generation.
- Purge unaccepted candidates after retention; terminal job, AI Usage, completed Seed reservation/ledger, and diagnostic history follow the use case's AI Data Retention period while current Seed balances remain protected.
While generation is active, the Recipe/Meal image dialog shows a single persistent checklist—Reserve AI Seeds → Prepare image details → Submit to the AI provider → Generate the image → Validate the generated image → Ready for review. It does not also show a separate current-stage spinner/status block. Errors and recovery guidance continue to use the normal status area because they require information beyond the checklist state.
AI Seed terminology
Every user-facing occurrence of AI Seeds uses the shared tooltip text:
AI Seeds are Blackcap's credits for AI features. Each AI action shows its AI Seed cost before confirmation.
Existing API Token terminology is unchanged. Provider-reported tokens are explicitly labeled as provider usage.
Recipe-scoped image state
Blackcap keeps recipe-facing AI image preferences and outcomes separate from the recipe content tables in ai_recipe_image_state. Each organization/recipe pair stores the latest image notes, current state, last success and failure job references, last candidate, profile, provider/model, error category/message, and user reference. Detailed request history remains in ai_jobs, including client request ID, provider response ID, retry lineage, prompt snapshot, cost, and provider result. Manual recipe drafts use their aidraft_* identity and transfer the state to the saved recipe ID when the recipe is created.
Only actual provider timeouts are eligible for the Retry action. Configuration, validation, authentication, safety, and other data errors remain recorded but cannot be retried as the same request. A user may correct the profile or choose another profile and begin a new generation request instead.
Provider deployment and configuration
Application update
Copy the updated files into the Blackcap installation, update the Python environment, and restart the application.
cd /opt/Blackcap
source /opt/blackcap_env/bin/activate
pip install -r requirements.txt
sudo systemctl restart inky_admin.service
For the cloud requirements set, use requirements-cloud.txt instead. The update adds the official openai>=2.46.0 and google-genai>=2.13.0 packages. These minimums intentionally move existing environments to current SDK lines that support the configured GPT Image 2 and Gemini Interactions API paths. Both adapters lazy-import their SDK, so only a configured provider is exercised at runtime.
Schema migrations run through the existing migration framework and are idempotent on SQLite and PostgreSQL. Migration 251 adds the common durable AI job/interaction state used by image generation and the other AI use cases. No standalone SQL command is required.
Configure providers
- Sign in as a System Admin.
- Open Configuration → Platform → AI.
- Add an OpenAI and/or Gemini connection and enter the API key.
- Test the connection.
- Assign each enabled Medium/High profile to a connection and supported model.
- Configure organization monthly allotments or manually grant organization/personal AI Seeds.
- Create or edit a manually entered recipe and perform one controlled generation.
Do not place provider keys in browser-visible configuration, URLs, job payloads, logs, or documentation. Use the platform configuration screen so Blackcap encrypts the secret using its existing secret-management path.
Optional live validation
Normal tests use mocked providers and cannot incur provider cost. To run the explicit paid checks:
export BLACKCAP_RUN_LIVE_AI_TESTS=1
export OPENAI_API_KEY='...'
export BLACKCAP_OPENAI_IMAGE_MODEL='...'
export GEMINI_API_KEY='...'
export BLACKCAP_GEMINI_IMAGE_MODEL='...'
PYTHONPATH=. pytest -q tests/test_ai_live_providers.py
As of July 2026, the seeded suggestions are OpenAI gpt-image-2 and Gemini gemini-3.1-flash-image. Confirm provider availability when deploying. Model selection remains configuration-driven so a later model change does not require application code changes.
Operational storage and purge
Unused generated candidates are stored below data/ai_generated_images/<organization_id>/ and are removed by the existing scheduled purge after the configured retention period. Accepted images enter the standard recipe cache path. Active provider or recovery jobs block lifecycle purge until the job reaches a safe terminal state. Terminal AI jobs, AI Usage, completed job-linked Seed reservations/ledger entries, and diagnostic evidence now follow the AI use case's AI Data Retention period. Live Seed Accounts and balance buckets remain protected so retention cleanup cannot change a current balance; stale empty accounts whose user/organization scope no longer exists can be removed after the conservative longest-use-case retention window.
AI administration verification after deployment
The completed administration follow-up does not add another migration or infrastructure dependency. After copying the changed files and restarting Blackcap:
- Open Administration → AI Usage and confirm the report loads with organization-authorized scope, server-side paging, sticky headers, and the contextual horizontal scrollbar.
- As a System Admin, confirm provider request IDs and provider-reported input/output/image token counts are visible. Confirm the same fields are absent for an Org Admin.
- Open
/api-tester, select AI Usage, and run the read-only AI Usage and balance endpoints with test data. - Open Administration → Database, expand AI, and confirm all 16 AI/support resources are listed. Open AI Usage Events and verify protected JSON payload columns are not available.
- Run the focused AI tests and regression suite
2026.08.09.19on both SQLite and PostgreSQL deployments.
Recipe image selection and upload continue to use the normal cache rebuild workflow; this follow-up does not add display-capability-specific cache skipping.