Building an AI Image Generation App with Large Language Models and AI Coding Tools
Learn how to build a customizable AI image generation application using Python, a large language model for prompt optimization, and AI-assisted coding tools. This practical guide covers the architecture, environment setup, API key management, core implementation, and improvements for concurrency, storage, and reliability.
AI image generation has evolved from an experimental novelty into a practical productivity tool. Many platforms let users generate images from a short text description, but ready-made tools may not provide the flexibility needed for custom business workflows.
For developers with some technical experience who are new to AI application development, combining a large language model (LLM) with an AI coding tool offers a practical way to build a dedicated image generation application. This approach provides greater control over the workflow while helping developers understand how its components work.
This guide explains the architecture, setup, and implementation of an AI image generation assistant, followed by improvements for production use.
1. Understanding the Core Architecture
A useful development approach combines an advanced LLM with an AI coding tool. These components serve different purposes: the LLM interprets user intent within the application, while the coding tool helps developers implement the software.
The application then calls a text-to-image API to generate the image.
The LLM as a Prompt Optimization Engine
In a conventional text-to-image workflow, users often need to write detailed prompts themselves. An LLM can act as a prompt engineering engine, turning a simple description into a more structured image prompt that includes lighting, composition, materials, and artistic style.
The LLM can also serve as the application’s conversational layer. By managing context across multiple turns, it can help interpret a user’s requests to revise a generated image.
AI Coding Tools as Development Assistants
For beginners, creating a project structure, writing HTTP requests, and parsing JSON responses can be time-consuming and error-prone.
AI coding tools provide LLM-based assistance for these tasks. Developers can describe requirements in natural language to generate project scaffolding, implement functions, or investigate errors and receive suggested fixes.
This reduces the amount of routine implementation work and allows developers to focus more closely on business logic. Generated code still needs to be reviewed and adjusted for the application and its APIs.
2. Preparing the Development Environment
Before implementing the application, set up a Python environment and obtain access to the model services.
Install Python and Dependencies
Python is a practical choice because of its libraries for HTTP requests and image processing. The example assumes Python 3.8 or later and a configured package manager.
Install the dependencies:
pip install requests pillow
requestshandles calls to the model APIs.pillowcan be used for image post-processing or saving images locally.
The core example below uses requests; image processing and local storage can be added afterward.
Manage API Keys Securely
Obtain API keys from the relevant LLM and image generation providers. Do not hard-code production credentials in source code. Supply them through environment variables instead:
export LLM_API_KEY="your_api_key_here"export IMAGE_API_KEY="your_image_key_here"
3. Implementing the AI Image Generation Assistant
The core workflow has two steps:
- Use the LLM to convert the user’s idea into a detailed English image prompt.
- Send the optimized prompt to a text-to-image API and return the generated image URL.
The following abstract example illustrates this workflow. The endpoint strings and model identifier are placeholders, not working service addresses. Replace them with values from the relevant API documentation, and verify that the request and response formats match your providers.
import osimport requestsimport json# Read credentials from environment variables.# Replace endpoint placeholders with the relevant provider endpoints.LLM_API_URL = "YOUR_LLM_CHAT_COMPLETIONS_ENDPOINT"IMAGE_GEN_URL = "YOUR_IMAGE_GENERATION_ENDPOINT"LLM_API_KEY = os.getenv("LLM_API_KEY")IMAGE_API_KEY = os.getenv("IMAGE_API_KEY")def generate_optimized_prompt(user_idea: str) -> str:"""Use an LLM to turn a simple idea into a detailed English image prompt."""headers = {"Authorization": f"Bearer {LLM_API_KEY}","Content-Type": "application/json"}payload = {"model": "advanced-llm-model", # Placeholder model identifier"messages": [{"role": "system","content": ("You are an expert AI image prompt engineer. Expand ""the user's simple description into a professional ""English prompt that includes details, lighting, ""materials, and artistic style. Return only the ""prompt, without additional explanations.")},{"role": "user","content": user_idea}]}try:response = requests.post(LLM_API_URL,headers=headers,json=payload,timeout=30)response.raise_for_status()result = response.json()return result["choices"][0]["message"]["content"].strip()except requests.exceptions.RequestException as e:print(f"LLM API request failed: {e}")return Nonedef generate_image(prompt: str) -> str:"""Call a text-to-image API and return the generated image URL."""headers = {"Authorization": f"Bearer {IMAGE_API_KEY}","Content-Type": "application/json"}payload = {"prompt": prompt,"n": 1,"size": "1024x1024"}try:response = requests.post(IMAGE_GEN_URL,headers=headers,json=payload,timeout=60)response.raise_for_status()result = response.json()return result["data"][0]["url"]except requests.exceptions.RequestException as e:print(f"Image generation failed: {e}")return Nonedef main():user_idea = "A cat playing guitar in a cyberpunk city"print(f"Original user idea: {user_idea}")print("Optimizing the prompt with the LLM...")pro_prompt = generate_optimized_prompt(user_idea)if not pro_prompt:print("Prompt optimization failed. Stopping the workflow.")returnprint(f"Optimized prompt: {pro_prompt}")print("Calling the image generation model...")image_url = generate_image(pro_prompt)if image_url:print(f"Image generated successfully. View it here: {image_url}")else:print("Image generation failed.")if __name__ == "__main__":main()
How the Code Works
generate_optimized_prompt() sends the user’s description to the LLM with a system instruction that defines the desired output. It extracts the resulting prompt from the response.
generate_image() passes that prompt to the image generation service. In this illustrative response format, the generated image URL is returned in data[0]["url"].
Both functions set request timeouts and call raise_for_status() to detect unsuccessful HTTP responses. If a request fails, the function prints an error and returns None. The main workflow stops if prompt optimization fails and reports whether image generation succeeds.
This is a starting point rather than a production-ready integration. Its exception handling covers request failures, but the response parsing assumes the illustrated JSON structure.
During development, an AI coding tool can help produce this type of implementation. For example, a developer might ask:
Write a Python function that calls an LLM API to generate a text-to-image prompt. Include exception handling.
The tool can generate a draft, which the developer can then review and adapt to the selected API.
4. Improvements and Best Practices for Production
Once the basic workflow is working, the next priorities are responsiveness, persistent storage, and resilience.
Introduce Asynchronous Requests
LLM inference and image generation can take tens of seconds. Blocking, synchronous requests can make an application feel slow and limit its ability to handle concurrent work.
Refactoring the request code with asyncio and aiohttp allows the application to support concurrent image generation workflows without blocking on each network request.
Within an individual workflow, image generation still depends on the optimized prompt. Asynchronous execution primarily helps the application handle multiple workflows at once.
Use Cloud Services for Storage and Task Management
Generated images should not remain accessible only through temporary URLs. Download them and upload them to an object storage service for persistent storage.
A content delivery network (CDN) can support efficient image delivery, while object storage provides long-term retention.
For long-running generation jobs, a message queue can decouple task submission from processing. This helps the application handle image generation work asynchronously and improve overall throughput.
Add Retry and Fallback Strategies
Network instability and overloaded model services can cause API calls to fail. Implement retries with exponential backoff to handle recoverable failures.
If repeated attempts fail, use a fallback such as a placeholder image or a clear, user-friendly error message. The goal is to handle failures predictably rather than allowing them to disrupt the application.
5. Conclusion
Building an AI image generation application offers more flexibility than relying solely on a ready-made tool. An LLM can translate user intent into detailed image prompts, while an AI coding tool can assist with the implementation of API calls and application logic.
Together, these tools give developers a practical route to a customizable image generation workflow. The basic Python implementation establishes the core process; asynchronous requests, persistent storage, and retry strategies help move it toward production use.
More broadly, learning to orchestrate AI services through APIs and code develops a reusable engineering skill: integrating model capabilities into applications that address specific user and business needs.
