### Image Prompt Iteration Example Source: https://docs.bfl.ai/guides/prompting_unified_basics This example demonstrates how to refine an image prompt iteratively. Start with a basic description and progressively add details like setting, style, and additional elements to achieve a more specific and desired outcome. ```N/A ``` -------------------------------- ### Example Prompt for Image Generation Source: https://docs.bfl.ai/guides/prompting_unified_reference An example prompt demonstrating the use of camera terms, lens settings, and lighting conditions to guide AI image generation. ```text Shot on Hasselblad X2D, 80mm lens, f/2.8, natural lighting ``` -------------------------------- ### FLUX.2 [klein] Style Training Example Source: https://docs.bfl.ai/llms.txt Technical guide for training style LoRAs on FLUX.2 [klein] models with a Graphic Impressions style example. ```APIDOC ## FLUX.2 [klein] Style Training Example This technical guide provides a step-by-step example of training style LoRAs on FLUX.2 [klein] models. It focuses on achieving a 'Graphic Impressions' style, demonstrating the process with practical instructions and code snippets. ### Example Focus - **Style LoRA Training**: Learn to train LoRAs for specific artistic styles. - **Graphic Impressions Style**: A practical example demonstrating the training process for this style. - **Technical Implementation**: Detailed steps and code for replicating the training. ``` -------------------------------- ### cURL Quick Start for Outpainting Source: https://docs.bfl.ai/flux_tools/flux_outpainting Submit an outpainting request using cURL and poll for the result. This example demonstrates constructing the JSON payload and making the API calls. ```bash IMAGE_B64="$(base64 < /path/to/input.png | tr -d '\n')" jq -n \ --arg img "$IMAGE_B64" \ '{ input_image: $img, width: 1024, height: 1024, reference_offset_x: 100, reference_offset_y: 50, output_format: "png" }' > /tmp/outpaint_request.json curl -sS -X POST "https://api.bfl.ai/v1/flux-tools/outpainting-v1" \ -H "accept: application/json" \ -H "Content-Type: application/json" \ -H "x-key: $BFL_API_KEY" \ --data-binary @/tmp/outpaint_request.json # Poll for the result curl -sS "https://api.bfl.ai/v1/get_result?id=YOUR_TASK_ID" \ -H "accept: application/json" \ -H "x-key: $BFL_API_KEY" ``` -------------------------------- ### GFX_IMP Dataset Caption Example 2 Source: https://docs.bfl.ai/flux_2/flux2_klein_training_example Example caption for GFX_IMP (2).txt, featuring a trigger word and a description of a person by a window. ```text GFX_IMPR5N. Medium Shot Profile Left of a shirtless person standing beside a multi-pane window. The person occupies the right half of the frame, torso angled slightly toward the window, head bowed with eyes closed. Face details: oval-to-long face shape, sharp jawline, pointed chin, defined cheekbones, medium forehead height, visible brow ridge, thick eyebrows, closed eyelids with hooded lids, straight narrow nose bridge, small nostrils, thin lips with mouth closed, clean-shaven jaw and upper lip, short hair with a messy fringe, visible ear with average size. The window fills the left background with vertical and horizontal muntins, while hanging drapery and wall panels appear in the upper right background. ``` -------------------------------- ### GFX_IMP Dataset Caption Example 1 Source: https://docs.bfl.ai/flux_2/flux2_klein_training_example Example caption for GFX_IMP (1).txt, including a trigger word and detailed description of a person. ```text GFX_IMPR5N. Waist Up Medium Shot Three Quarter Right of a person wearing a wide-brim cowboy hat and a suit jacket over a collared shirt and tie. The person is centered in the frame with shoulders squared and head slightly tilted upward, looking past the camera. Face details: long face shape, angled jawline, narrow pointed chin, prominent cheekbones, medium-height forehead, pronounced brow ridge, thick straight eyebrows, deep-set almond eyes, straight narrow nose bridge, narrow nostrils, thin upper lip with fuller lower lip, mouth slightly open with teeth not visible, clean-shaven cheeks and chin, short hair visible at the sides under the hat, medium ears slightly protruding. Wooden building facades sit in the left and right background, with a utility pole and wires behind the person on the right side, and scattered clouds in the sky. ``` -------------------------------- ### Get Task Result Response Example Source: https://docs.bfl.ai/api-reference This is an example of a successful response when retrieving a task result. The 'result' field will be populated when the task is complete. ```json { "id": "", "result": null, "progress": 123, "details": {}, "preview": {} } ``` -------------------------------- ### Tabbed Setup Steps Component Source: https://docs.bfl.ai/api_integration/mcp_integration A React component for displaying setup steps using tabs. It manages active tab state, updates URL query parameters, and includes a copy-to-clipboard feature for keys. ```jsx import { useState, useEffect } from "react"; export const SetupSteps = ({tabs, queryParam = 'client'}) => { const [activeId, setActiveId] = useState(tabs[0].id); const [copiedKey, setCopiedKey] = useState(null); const active = tabs.find(t => t.id === activeId) ?? tabs[0]; useEffect(() => { if (typeof window === 'undefined') return; const params = new URLSearchParams(window.location.search); const fromUrl = params.get(queryParam); if (fromUrl && tabs.some(t => t.id === fromUrl)) { setActiveId(fromUrl); } }, [queryParam, tabs]); const selectTab = id => { setActiveId(id); if (typeof window !== 'undefined') { const params = new URLSearchParams(window.location.search); params.set(queryParam, id); const newUrl = `${window.location.pathname}?${params.toString()}${window.location.hash}`; window.history.replaceState(null, '', newUrl); } }; const copy = (key, value) => { if (typeof navigator !== 'undefined' && navigator.clipboard) { navigator.clipboard.writeText(value); setCopiedKey(key); setTimeout(() => setCopiedKey(curr => curr === key ? null : curr), 1500); } }; return
{tabs.map(tab => { const selected = activeId === tab.id; return ; })}
{/* Content for the active tab would go here, potentially using the 'active' variable */}
; }; ``` -------------------------------- ### Example Prompt with Text in Image Source: https://docs.bfl.ai/guides/prompting_unified_basics This example demonstrates how to include specific text within an image prompt. Placing text in quotation marks signals FLUX to render it as visible text in the final image. ```json { "img": "https://cdn.sanity.io/images/2gpum2i6/production/b3300d8897ec5682f886be1c9576c7a7084d775e-1504x1008.png", "prompt": "A photorealistic still life of matchsticks arranged on a beige paper background. On the left, a group of burnt-out matchsticks leaning together with charred black tips and rising smoke. In the center, a single unlit match standing upright, separating the two groups. On the right, a neat row of fresh red-tipped matches. Below the scene, bold serif typography reads \"The Importance Of Being Non-Aligned\". Warm, soft studio lighting with subtle shadows." } ``` ```json { "img": "https://cdn.sanity.io/images/2gpum2i6/production/e55dd7892b9ef7e9a3ee0f46ac6cf77b1d508fa8-1504x1008.png", "prompt": "An anime-style illustration of a cute snake being poked on the head by a human finger. The snake has big blue eyes and a gentle smile. A white speech bubble reads \"Wow, what are you doing here?! I am sleeping\". Sandy desert background with warm tones. Soft cel-shading, expressive cartoon style." } ``` ```json { "img": "https://cdn.sanity.io/images/2gpum2i6/production/b7f4b87f8eb8d23633fe09fdc6ca83ed71d4acdf-1504x1008.png", "prompt": "A humorous infographic-style meme image with the bold headline \"WHY DOES THIS CHAT KEEP GETTING RESET\" at the top. The scene shows a person at a desk squeezed between two large server towers labeled \"MEMORY LIMIT\" and \"TOKEN BUDGET\". In the center, a red warning triangle reads \"DELETION ZONE\" with fire and emojis. A green banner says \"YOUR BEAUTIFUL IMAGES\" and a \"404 IMAGES LOST\" error badge appears on the right. Three info boxes at the bottom with satirical descriptions. Clean digital illustration style with blue and teal tones." } ``` ```json { "img": "https://cdn.sanity.io/images/2gpum2i6/production/8771cfc4a0d0cd5257a452926c1d722c36e8b411-1504x1008.png", "prompt": "A set of five car air freshener stickers on a gray background, each shaped differently and spelling out \"FLUX 2\". A blue star-burst shape with \"F\" and \"Fast\", a red droplet with a rainbow \"L\" and \"Lightweight\", a holographic rounded square with green \"U\" and \"Upscaled\", a green Christmas tree shape with \"X\" and \"Xtra\", and a round red prohibition sign with a banana and the number \"2\". Glossy sticker aesthetic with subtle shadows." } ``` -------------------------------- ### Structured Prompting Example Source: https://docs.bfl.ai/flux_2/flux2_text_to_image Use JSON-structured prompts for precise control over image generation, ideal for production workflows and automation. This example defines subject, background, lighting, style, camera angle, and composition. ```json { "subject": "Mona Lisa painting by Leonardo da Vinci", "background": "museum gallery wall, ornate gold frame", "lighting": "soft gallery lighting, warm spotlights", "style": "digital art, high contrast", "camera_angle": "eye level view", "composition": "centered, portrait orientation" } ``` -------------------------------- ### Prompt Example: Samsung Galaxy Advertisement Source: https://docs.bfl.ai/guides/usecases_t2i_typography_design Example prompt for generating a product advertisement. Specifies headline, subtext, visual elements, and overall aesthetic. ```text Samsung Galaxy S25 Ultra product advertisement, 'Ultra-strong titanium' headline, 'Shielded in a strong titanium frame, your Galaxy S25 Ultra always stays protected' subtext, close-up of phone edge showing titanium frame, dark gradient background, clean minimalist tech aesthetic, professional product photography ``` -------------------------------- ### Prompt Example: Groovy Retro Poster Source: https://docs.bfl.ai/guides/usecases_t2i_typography_design Example prompt for a retro-style poster. Details the quote, typography style, color palette, and overall aesthetic. ```text Groovy retro poster with the quote "If you love me let me sleep". Bold 70s typography in deep red and warm pink tones. Cream background and bold orange doodle around the text. Funky layout with playful shadow. Style: bold vintage aesthetic, dopamine decor ``` -------------------------------- ### Example Lighting Phrase: Overcast Light Source: https://docs.bfl.ai/guides/prompting_unified_reference Use this phrase to describe overcast light that creates even, shadow-free illumination. ```text overcast light creating even, shadow-free illumination ``` -------------------------------- ### Python Quick Start for Outpainting Source: https://docs.bfl.ai/flux_tools/flux_outpainting Submit an outpainting request using Python and poll for the result. Ensure your API key is set as an environment variable. ```python #!/usr/bin/env python3 import base64 import os import time import requests API_KEY = os.environ["BFL_API_KEY"] BASE = "https://api.bfl.ai" HEADERS = {"accept": "application/json", "x-key": API_KEY, "Content-Type": "application/json"} IMAGE_PATH = "/path/to/input.png" WIDTH, HEIGHT = 1024, 1024 REFERENCE_OFFSET_X = 100 # None = center horizontally REFERENCE_OFFSET_Y = 50 # None = center vertically with open(IMAGE_PATH, "rb") as f: image_b64 = base64.b64encode(f.read()).decode() payload = { "input_image": image_b64, "width": WIDTH, "height": HEIGHT, "output_format": "png", } if REFERENCE_OFFSET_X is not None: payload["reference_offset_x"] = REFERENCE_OFFSET_X if REFERENCE_OFFSET_Y is not None: payload["reference_offset_y"] = REFERENCE_OFFSET_Y submit = requests.post(f"{BASE}/v1/flux-tools/outpainting-v1", headers=HEADERS, json=payload) submit.raise_for_status() meta = submit.json() task_id = meta["id"] poll_url = meta.get("polling_url", f"{BASE}/v1/get_result?id={task_id}") while True: r = requests.get(poll_url, headers={"accept": "application/json", "x-key": API_KEY}) r.raise_for_status() result = r.json() status = result.get("status") if status == "Ready": print("Result URL:", result["result"]["sample"]) break if status in {"Error", "Request Moderated", "Content Moderated", "Task not found"}: raise RuntimeError(f"Outpainting failed with status: {status} | payload: {result}") time.sleep(1) ``` -------------------------------- ### Displaying Steps with Code Source: https://docs.bfl.ai/quick_start/get_started This snippet demonstrates how to render steps, including titles, descriptions, buttons, and code examples, within a grid layout. It handles dynamic styling based on step properties. ```javascript
s.wide) ? 'md:grid-cols-4' : 'md:grid-cols-3'} gap-4`}> {active.steps.map((step, i) => { const key = `${active.id}-${i}`; return
{step.number}

{step.title}

{step.button && {step.button.label} } {step.code &&

{step.code}
} {step.codes && step.codes.map((c, ci) => { const codeKey = `${key}-c${ci}`; return
{c.label && {c.label} } {c.value}
; })}
; })}
``` -------------------------------- ### Get Result Source: https://docs.bfl.ai/llms.txt An endpoint for getting generation task results. ```APIDOC ## GET /utility/get-result ### Description An endpoint for getting generation task results. ### Method GET ### Endpoint /utility/get-result ### Parameters #### Query Parameters - **task_id** (string) - Required - The ID of the generation task. ### Response #### Success Response (200) - **status** (string) - The status of the task (e.g., 'processing', 'completed', 'failed'). - **output_url** (string) - A URL to the generated image if the task is completed. - **error_message** (string) - An error message if the task failed. #### Response Example { "status": "completed", "output_url": "https://cdn.bfl.ml/images/final_result.png" } ``` -------------------------------- ### Multi-Reference Prompting Example 1 Source: https://docs.bfl.ai/guides/prompting_editing_multi_reference Generates a house for chickens using specified materials and applies a style from a reference image. This is useful for creating composite scenes with specific object and style requirements. ```javascript import { MultiRefMasonry } from "@/components/MultiRefMasonry"; ``` -------------------------------- ### FLUX API Integration Guide Source: https://docs.bfl.ai/llms.txt Essential guide for integrating with FLUX API endpoints, including endpoint selection, polling, and content handling. ```APIDOC ## FLUX API Integration Guide This guide provides essential information for integrating with FLUX API endpoints. It covers best practices for selecting the appropriate endpoints for your needs, strategies for polling task statuses, and guidelines for handling API responses, including content management. ### Key Concepts - **Endpoint Selection**: Choose endpoints based on your specific use case (e.g., generation, editing, inpainting). - **Task Polling**: Utilize the `/utility/get-result` endpoint to monitor the status of asynchronous tasks. - **Content Handling**: Process image data efficiently, whether it's base64 encoded in requests or accessed via URLs in responses. - **Error Handling**: Refer to the `/api_integration/errors.md` for detailed information on HTTP status codes and error response formats. ``` -------------------------------- ### Prompt Example: White Paper Poster Source: https://docs.bfl.ai/guides/usecases_t2i_typography_design Example prompt for a poster with text and an illustration. Specifies the quote, drawing style, and potential visual artifacts. ```text A White Paper with the Text "Crazy to think all this started with an Avocado." and a really bad drawing with diffusion artifacts of a avocado ``` -------------------------------- ### Prompt Example: Women's Health Magazine Cover Source: https://docs.bfl.ai/guides/usecases_t2i_typography_design Example prompt for creating a magazine cover. Includes issue details, headline, feature text, callouts, and specifies photography style. ```text Women's Health magazine cover, April 2025 issue, 'Spring forward' headline, woman in green outfit sitting on orange blocks, white sneakers, 'Covid: five years on' feature text, '15 skincare habits' callout, professional editorial photography, magazine layout with multiple text elements ``` -------------------------------- ### Multi-Reference Masonry Example Source: https://docs.bfl.ai/guides/prompting_editing_multi_reference Composites elements from multiple input images into a result image based on a detailed prompt. Useful for complex scene creation. ```jsx ``` -------------------------------- ### Example API Call for Finetune Inference Source: https://docs.bfl.ai/flux_2/flux2_lora_inference This curl command demonstrates how to make an API call to an inference endpoint using a specific finetune. It includes placeholders for the finetune ID and strength, and a sample prompt that utilizes a trigger phrase if one is set. ```bash curl -X POST \ -H "Authorization: Bearer $BFL_API_KEY" \ -H "Content-Type: application/json" \ --data '{ "prompt": "TOK, a cat wearing a hat", "max_tokens": 100, "temperature": 0.7 }' \ https://api.bfl.ai/v1/engines/flux-2-7b-kv-finetuned/completions ``` -------------------------------- ### Download and Re-serve Image Pattern Source: https://docs.bfl.ai/api_integration/integration_guidelines This pattern demonstrates how to download a generated image from a BFL delivery URL, store it locally, and prepare it for serving from your own infrastructure. It includes error handling and unique filename generation. ```python import requests import os from datetime import datetime from typing import Dict, Any def download_and_store_image(result_url: str, local_path: str) -> str: """ Download image from BFL delivery URL and store locally """ response = requests.get(result_url) response.raise_for_status() with open(local_path, 'wb') as f: f.write(response.content) return local_path def handle_generation_result(result: Dict[str, Any]) -> Dict[str, Any]: """ Process generation result and store image locally """ if result['status'] == 'Ready': sample_url = result['result']['sample'] # Generate unique filename timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"generated_image_{timestamp}.jpg" local_path = os.path.join("./images", filename) # Ensure directory exists os.makedirs(os.path.dirname(local_path), exist_ok=True) # Download and store stored_path = download_and_store_image(sample_url, local_path) # Now serve from your own infrastructure return { 'status': 'ready', 'local_path': stored_path, 'public_url': f"https://yourdomain.com/images/{filename}" } return result ``` ```javascript const fs = require('fs'); const path = require('path'); const https = require('https'); async function downloadAndStoreImage(resultUrl, localPath) { return new Promise((resolve, reject) => { const file = fs.createWriteStream(localPath); https.get(resultUrl, (response) => { response.pipe(file); file.on('finish', () => { file.close(); resolve(localPath); }); file.on('error', (err) => { fs.unlink(localPath, () => {}); // Delete incomplete file reject(err); }); }).on('error', reject); }); } async function handleGenerationResult(result) { if (result.status === 'Ready') { const sampleUrl = result.result.sample; // Generate unique filename const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const filename = `generated_image_${timestamp}.jpg`; const localPath = path.join('./images', filename); // Ensure directory exists fs.mkdirSync(path.dirname(localPath), { recursive: true }); // Download and store const storedPath = await downloadAndStoreImage(sampleUrl, localPath); // Return path for serving from your infrastructure return { status: 'ready', localPath: storedPath, publicUrl: `https://yourdomain.com/images/${filename}` }; } return result; } ``` -------------------------------- ### Step 1: Generate a single coffee mug Source: https://docs.bfl.ai/guides/usecases_t2i_json_prompting Initial JSON prompt to generate a single minimalist ceramic coffee mug in a studio setting. Specifies subject details, style, color palette, lighting, and camera settings. ```json { "scene": "Professional studio product photography setup with polished concrete surface", "subjects": [ { "description": "Minimalist ceramic coffee mug with steam rising from hot coffee inside", "pose": "Stationary on surface", "position": "Center foreground on polished concrete surface", "color_palette": ["matte black ceramic"] } ], "style": "Ultra-realistic product photography with commercial quality", "color_palette": ["matte black", "concrete gray", "soft white highlights"], "lighting": "Three-point softbox setup creating soft, diffused highlights with no harsh shadows", "mood": "Clean, professional, minimalist", "background": "Polished concrete surface with studio backdrop", "composition": "rule of thirds", "camera": { "angle": "high angle", "distance": "medium shot", "focus": "Sharp focus on steam rising from coffee and mug details", "lens-mm": 85, "f-number": "f/5.6", "ISO": 200 } } ``` -------------------------------- ### Get Result Source: https://docs.bfl.ai/api-reference/utility/get-result Retrieve the result of a generation task using its ID. ```APIDOC ## GET /v1/get_result ### Description An endpoint for getting generation task result. ### Method GET ### Endpoint /v1/get_result ### Parameters #### Query Parameters - **id** (string) - Required - Task id for retrieving result ### Response #### Success Response (200) - **id** (string) - Task id for retrieving result - **status** (StatusResponse) - The current status of the task. - **result** (any) - The result of the task, if available. - **progress** (number) - The progress of the task, if available. - **details** (object) - Additional details about the task, if available. - **preview** (object) - A preview of the task result, if available. #### Error Response (422) - **detail** (array) - A list of validation errors. ### Response Example ```json { "id": "task_12345", "status": "Ready", "result": { "generated_text": "This is the generated text." }, "progress": 100, "details": {}, "preview": {} } ``` ``` -------------------------------- ### Get User Credits Source: https://docs.bfl.ai/api-reference/get-the-users-credits Retrieve the current credit balance for the authenticated user. ```APIDOC ## GET /v1/credits ### Description Get the user's credits. This endpoint retrieves the current credit balance for the authenticated user. ### Method GET ### Endpoint /v1/credits ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **credits** (number) - User's current credit balance #### Response Example ```json { "credits": 100.5 } ``` ### Security - APIKeyHeader: x-key ``` -------------------------------- ### Windsurf MCP Configuration Source: https://docs.bfl.ai/api_integration/mcp_integration Paste this JSON into your `~/.codeium/windsurf/mcp_config.json` file. Note that Windsurf uses `serverUrl`. ```json { "mcpServers": { "FLUX": { "serverUrl": "https://mcp.bfl.ai" } } } ``` -------------------------------- ### GET /v1/finetune_details Source: https://docs.bfl.ai/api-reference/utility/finetune-details Retrieves details about the training parameters and other metadata for a specific finetune ID. ```APIDOC ## GET /v1/finetune_details ### Description Get details about the training parameters and other metadata connected to a specific finetune_id that was created by the user. ### Method GET ### Endpoint /v1/finetune_details ### Parameters #### Query Parameters - **finetune_id** (string) - Required - The ID of the finetune to retrieve details for. ### Response #### Success Response (200) - **finetune_details** (object) - Details about the parameters used for finetuning #### Response Example ```json { "finetune_details": { "example_param_1": "value1", "example_param_2": 123 } } ``` #### Error Response (422) - **detail** (array) - Contains validation error information. #### Error Response Example ```json { "detail": [ { "loc": [ "query", "finetune_id" ], "msg": "field required", "type": "value_error.missing" } ] } ``` ``` -------------------------------- ### Install MCP Skill in Cursor Source: https://docs.bfl.ai/api_integration/mcp_integration Use this command to add the MCP skill when using Cursor. Alternatively, manually place skill files in the .cursor/skills/ directory. ```bash npx skills add black-forest-labs/skills ``` -------------------------------- ### Get Task Result Source: https://docs.bfl.ai/api-reference Use this endpoint to retrieve the status and result of a previously submitted task using its ID. ```bash curl --request GET \ --url https://api.bfl.ai/v1/get_result ``` -------------------------------- ### Prompt for Camera and Lens Simulation (Canon) Source: https://docs.bfl.ai/guides/prompting_unified_style Example prompt specifying camera model, lens range, time of day, and depth of field for photorealistic results. ```text Canon 5D Mark IV, 24-70mm at 35mm, golden hour, shallow depth of field ``` -------------------------------- ### Install MCP Skill in Claude Code Source: https://docs.bfl.ai/api_integration/mcp_integration Use this command to add the MCP skill when using Claude Code. ```bash /plugin marketplace add black-forest-labs/skills /plugin install flux-best-practices@bfl-skills ``` -------------------------------- ### Prompt for Repainting Walls and Changing Flooring Source: https://docs.bfl.ai/guides/usecases_editing_interior_design Use this prompt to instruct FLUX.2 to repaint a room and change its flooring. This example demonstrates a common interior design modification. ```text The room is repainted and on the floor there is rustic wooden parquet ``` -------------------------------- ### Example Lighting Phrase: Golden Hour Backlighting Source: https://docs.bfl.ai/guides/prompting_unified_reference Use this phrase to describe golden hour backlighting with lens flare. ```text golden hour backlighting with lens flare ```