Abstract: Build a small window with Python and Tkinter that calls the APIYI image generation API. Enter a description, preview it locally, and save the result as a PNG.
The local tool handles the prompt, dimensions, file naming, and results directory, while image generation happens in the cloud. APIYI apiyi.com receives your request, calls the model to generate an image, and returns the result to your program. The first version only needs three things: a model, a request, and a result area. First make sure the API key lives only in the local request layer, then get the path from “enter a description → click a button → see an image → one more PNG on disk” working end to end, and you’re done.
Two things need to be made clear up front. First, the prompt and reference image are still sent to the server according to the request protocol, so this isn’t offline image generation, and the assets won’t always remain only on your computer. Second, image generation requests are synchronous, so you can’t blindly resend after a timeout.

Knowledge Map and Reading Order
| No. | Content | Output of This Section | Relationship to Previous and Next Sections |
|---|---|---|---|
| 1 | Why build a local tool to call the image API | Clarify the division of work between local and cloud | Sets the scope; all later code revolves around this division |
| 2 | Connect a text-to-image request to a button | A runnable app.py | Core part; Sections 3 and 4 both build on it |
| 3 | Confirm the first call succeeds | No-cost UI acceptance test, offline unit test, one real call | Validates Section 2 and explains how to handle timeouts |
| 4 | Add a reference image for image editing | Change the request from JSON to multipart | Extends the window from Section 2 |
| 5 | How to choose between chat clients and self-built tools | Selection criteria and cost-checking method | Read as needed; can be read on its own |
Suggested reading: start with Section 1, write the code from Section 2, then verify it using the methods in Section 3. Section 4 is for readers who need image editing. Section 5 is for readers still wondering “should I build my own?” and can be skipped for now.
To Know
| Term | Explanation |
|---|---|
| API key | A key that lets APIYI identify the caller and verify account permissions |
| Images API | A set of endpoints that accept text-to-image or image-editing requests |
| Tkinter | Python’s built-in GUI interface; lets you build desktop windows with input fields, buttons, and labels |
| Base64 | A format that encodes binary content as text; images need to be decoded back into bytes before saving |
| Synchronous request | The connection stays open after the request is sent while waiting for the result; the client doesn’t get a task ID, so it can’t check back later |
| Worker thread | Runs time-consuming work outside the main UI thread; UI updates still happen on the main thread |
| multipart | An encoding method that sends text fields and one or more files in a single HTTP request |
1 Why build your own local tool to call the image API
If you generate images often, you probably keep reusing the same size, the same prompt template, and the same output folder. Say you produce a batch of e-commerce placeholder images every week — always square 1024×1024, always saved to the same path. In a chat client, you end up restating the requirements, downloading the file manually, and renaming it manually every single time. Write yourself a small window, and you can lock all of that repetition in place.
Here’s how the work splits up:
- Your machine handles: entering the prompt, choosing size and quality, naming the file, selecting the output directory, previewing the result, and recording metadata.
- The cloud handles: model inference and image generation. The request goes through APIYI to the matching model channel, and the result comes back as Base64.
- What always gets uploaded: the prompt, plus the reference image whenever you’re editing an image.
A typical first version has just four elements: a description input box, a generate button, a preview area, and an output path. The example in this article is “generate a placeholder product image of a white porcelain cup on a light gray background, lit from the front-left, with empty space in front” — square 1024×1024, medium quality, PNG format, one image per request. The example model is gpt-image-2.6-sunburst on the APIYI channel.

2 Calling the API to Draw from a Local Tool: Wiring Text-to-Image Requests to a Button
2.1 What You’ll Need
Before you start, confirm four things:
- Python 3 and Tk are available: Run
python -m tkinterin your terminal. If a small test window pops up, Tk is working fine. - Have an API Key ready: Create a token in the APIYI apiyi.com console. The official-transfer page in section 2.6 requires a pay-as-you-go priority token, and the available groups include Default, image2Enterprise, and so on. A model being listed in the platform catalog doesn’t mean this key has permission to use it — you need to check both separately.
- Put the Key in an environment variable: On Windows PowerShell, the syntax is
$env:APIYI_API_KEY = '替换成自己的 Key'; on macOS and Linux you can useexport APIYI_API_KEY='替换成自己的 Key'. Don’t write your real Key into shared scripts, screenshots, or logs — you can also use the system’s credential manager instead. - Run the program in the same terminal: Environment variables are only valid for the current session. Switch to a different terminal window and you’ll need to set them again.
2.2 Request Parameters at a Glance
| Field | Value | Description |
|---|---|---|
| Endpoint | POST /v1/images/generations |
Text-to-image path; use a different path for image editing |
| Authentication | Authorization: Bearer <Key> |
Key injected from an environment variable |
| Content-Type | application/json |
Text-to-image uses a JSON request body |
| model | gpt-image-2.6-sunburst |
Example model; refer to the model page and your group |
| size / quality | 1024x1024 / medium |
Square, medium quality |
| output_format / n | png / 1 |
One PNG per request |
| Return location | data[0].b64_json |
Raw Base64 string, without a data URI prefix |
Sunburst’s official relay returns b64_json directly, so you don’t need to send response_format. If you integrate other models later, you should write separate request and response adapters for each model. Don’t copy the size and field names here onto another model.
2.3 Complete Minimal Window Code
Save the code below as app.py, then run python app.py in a terminal where the environment variable has been set. Keep the UI part inside the main() function so that when the unit tests in Section 3 import generate(), they won’t pop up a window.
import base64
import json
import os
import queue
import threading
import tkinter as tk
import uuid
from pathlib import Path
from urllib.request import Request, urlopen
API_URL = "https://api.apiyi.com/v1/images/generations" # APIYI unified endpoint
def generate(prompt):
body = {
"model": "gpt-image-2.6-sunburst", "prompt": prompt,
"size": "1024x1024", "quality": "medium", "output_format": "png", "n": 1,
}
request = Request(
API_URL,
data=json.dumps(body).encode("utf-8"),
headers={
"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}",
"Content-Type": "application/json",
},
method="POST",
)
with urlopen(request, timeout=300) as response:
result = json.load(response)
data = base64.b64decode(result["data"][0]["b64_json"], validate=True)
if not data.startswith(b"\x89PNG\r\n\x1a\n"):
raise ValueError("接口没有返回 PNG")
directory = Path.cwd() / "outputs"
directory.mkdir(exist_ok=True)
path = directory / f"image-{uuid.uuid4().hex[:12]}.png"
pending = path.with_suffix(".part")
pending.write_bytes(data)
pending.replace(path)
return path
def main():
root = tk.Tk()
root.title("本地生图")
prompt_box = tk.Entry(root, width=56)
prompt_box.pack()
status = tk.Label(root, text="输入描述后点生成")
status.pack()
preview = tk.Label(root)
preview.pack()
results = queue.Queue()
def work(prompt):
try:
results.put((generate(prompt), None))
except KeyError as exc:
note = "请先设置 APIYI_API_KEY" if exc.args[0] == "APIYI_API_KEY" else "响应缺少图片字段"
results.put((None, note))
except Exception as exc:
results.put((None, f"请求或保存失败:{type(exc).__name__}"))
def start():
prompt = prompt_box.get().strip()
if not prompt:
status.config(text="请先输入描述")
return
button.config(state="disabled")
status.config(text="正在等待图片响应")
threading.Thread(target=work, args=(prompt,), daemon=True).start()
def poll():
try:
path, error = results.get_nowait()
except queue.Empty:
root.after(150, poll)
return
button.config(state="normal")
if error:
status.config(text=error)
else:
try:
image = tk.PhotoImage(file=str(path)).subsample(3, 3)
except tk.TclError:
status.config(text=f"已保存,预览失败:{path}")
else:
preview.config(image=image)
preview.image = image
status.config(text=str(path))
root.after(150, poll)
button = tk.Button(root, text="生成", command=start)
button.pack()
root.after(150, poll)
root.mainloop()
if __name__ == "__main__":
main()
2.4 What This Code Does
generate() is a standalone function you can call on its own. It handles the request, the decoding, and the write to disk, and has nothing to do with the UI. It first confirms the bytes it got back really are an image by checking the PNG file signature, then writes them to a temporary .part file, and only renames that to .png at the very end. That way, even if a write fails halfway through, you won’t end up with an unopenable “half-captured screenshot” sitting in the outputs directory.
On the UI side, clicking the button first greys it out to prevent duplicate submissions. The actual network request runs on a worker thread, and the result goes into a queue. The main thread checks that queue every 150 milliseconds with poll(), then updates the preview and the status. Tk widgets can only be touched from the main thread, which is why the worker thread never modifies the UI directly here. The preview image is scaled down by a factor of three with subsample(3, 3), but what gets saved to disk is the original image.
🚀 Quick Start: When you’re integrating this for the first time, it’s best to start with a single request on APIYI (apiyi.com) using the free trial credits available to new users. Once you’ve confirmed the key permissions and the grouping are fine, then go ahead and expand the feature set.
If you want to make this tool more convenient, you can keep building on it from here: let the user pick their own output directory; switch the filename to a “date plus short ID” format; and write a separate metadata file after each generation that records the model, size, quality, prompt, timestamp, and filename. Don’t store the key in the metadata, and don’t store bulky Base64 originals there either.
3 Verify the local tool’s first successful image generation API call
3.1 Test the UI before spending money
Temporarily replace generate() with a function that directly returns the path to an existing local PNG. Then click “Generate” and watch three things: does the button go gray first; can you still drag the window normally while waiting; and after it finishes, can you see the preview and the file path? This step only verifies the button, threading, and preview. It won’t verify decoding or saving.
3.2 Verify decoding and writing to disk offline
Use unittest.mock to replace urlopen so it returns JSON containing the Base64 for a known PNG, then call generate() in a temporary directory and compare the bytes in the generated file to see if they match:
import base64, io, json, os, tempfile, unittest
from pathlib import Path
from unittest import mock
import app
FAKE_PNG = b"\x89PNG\r\n\x1a\n" + b"test-bytes"
class GenerateTest(unittest.TestCase):
def test_saves_png(self):
body = json.dumps(
{"data": [{"b64_json": base64.b64encode(FAKE_PNG).decode()}]}
).encode()
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.dict(os.environ, {"APIYI_API_KEY": "test-key"}), \
mock.patch("app.urlopen", return_value=io.BytesIO(body)), \
mock.patch("app.Path.cwd", return_value=Path(tmp)):
path = app.generate("白瓷杯")
self.assertEqual(path.read_bytes(), FAKE_PNG)
self.assertEqual(path.suffix, ".png")
if __name__ == "__main__":
unittest.main()
Neither of the above mock setups can verify the gateway, API key, model permissions, or billing. In the end, you still need to send one real request and check three things: whether the file in outputs opens in an image viewer; whether it’s actually a PNG; and whether there’s a corresponding call record in the console log.
3.3 Synchronous timeouts and duplicate submissions
The Images call is synchronous, and the wait limit set in the code is 300 seconds. If the network drops or times out before you receive a response, the upstream may have already finished running, and may even have already billed you. A regular request ID is not an async task ID, so you can’t poll it to fetch the image. The right approach is to check the logs and billing first to confirm the status of that request, then decide whether to resend it.
| Failure point | Symptom | Suggested action |
|---|---|---|
| Timeout or disconnect before a response | Status bar shows request failed | Check logs and billing first; don’t resend unconditionally |
| Response received, decoding failed | Error says the response is missing fields or the signature doesn’t match | Check whether the model and response structure match |
| Decoded but writing to disk failed | Disk or permission error | If you saved a valid response separately, you can decode it again from that copy |
| Saved but preview failed | Status bar shows “Saved, preview failed” | The file is usable; this is a Tk preview issue |
Recovery flows like “the image was generated, but the download URL failed” only apply to channels that return URLs. Sunburst returns Base64 directly, so the focus is making sure the received data gets written to disk promptly. If you later add a task queue on the local machine, you’ll also need to set a concurrency limit and timeouts, and be clear about what “cancel” actually means. A queue only keeps the UI from freezing—it doesn’t magically add recovery capability to the upstream.
4 Adding a Reference Image: Upgrading a Local Tool from API Image Generation to Image Editing
Image editing uses a different endpoint, /v1/images/edits, and the request format switches from JSON to multipart. Add a “Choose File” button to the UI that accepts only valid PNG, JPEG, or WebP files by default. The file path string stays on your machine; what actually gets uploaded is the file’s contents.
The field rules are as follows: for a single reference image, use the image field; for multiple reference images, repeat the image[] field, and in the prompt spell out — in upload order — what each image should keep and what should change. Let the HTTP library generate the multipart boundary automatically; don’t write it by hand, or you’ll almost certainly get it wrong. Here’s a demo using requests:
import base64, os
import requests
with open("cup.png", "rb") as f:
resp = requests.post(
"https://api.apiyi.com/v1/images/edits", # APIYI image editing endpoint
headers={"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}"},
data={
"model": "gpt-image-2.6-sunburst",
"prompt": "保留白瓷杯的轮廓和构图,只将背景改成浅蓝色",
"size": "1024x1024", "quality": "medium",
"output_format": "png", "n": "1",
},
files={"image": ("cup.png", f, "image/png")},
# For multiple reference images, change to: files=[("image[]", (...)), ("image[]", (...))]
timeout=300,
)
resp.raise_for_status()
data = base64.b64decode(resp.json()["data"][0]["b64_json"])
A note: don’t manually set Content-Type in the request headers — let requests fill in the value with the boundary. Save the edited result as a new file rather than overwriting the original, then compare whether the subject was preserved and the background changed correctly. For the response fields of the image editing endpoint, refer to the specific model’s dedicated page. Also keep in mind that every edit is a fresh API request — multi-turn revisions don’t automatically carry over context from the previous round the way a chat does, so you need to resend the original image and the complete instructions each time.
5 How to Choose Between Chat Clients and Local Tools for API Image Generation
5.1 Decision Criteria
The key to deciding which approach to use is whether your task is “one-off exploration” or “repeated production.” If you’re just hunting for inspiration on the fly, an off-the-shelf chat client needs no installation or maintenance: you can tweak images as you chat, and it comes with an editor and image management built in. If you regularly produce product images at the same dimensions and want consistent naming by campaign ID and date, archiving the prompt, dimensions, and reference image together, then a self-built tool is the better fit.

| Dimension | Chat client | Self-built local tool |
|---|---|---|
| Getting started | No installation or maintenance | Requires writing code and configuring an API key |
| Best suited for | Composition exploration, iterating on images through chat, quick previews | Batch image generation with fixed parameters, consistent naming and archiving |
| Feature scope | The client’s built-in context, editor, and reference library | Only the parameters the API exposes, as determined by the model and routing |
| File management | Manual downloading and organizing | Automatically saved to a designated directory with metadata recorded |
| Cost basis | Free quota, subscription, or credits | Billed by usage; you need to check the actual bill |
Some features exclusive to the client aren’t guaranteed to be available through the API. Conversely, what a self-built tool can do is limited to the parameters the API exposes. So don’t assume that “building it locally is always cheaper.” Comparing actual cost and output quality only makes sense when the model, routing, parameters, and billing conditions all line up. When comparing results, use the same prompt and parameters that can be aligned, and record the sample count for each.
5.2 Differences in Public Pricing Figures
As of the 2026-11-23 check, gpt-image-2.6-sunburst had several different public pricing figures:
- APIYI’s public model master list shows it under the images protocol at $0.20/request.
- Reading back the public pricing API on the same day, the same record contained both
model_price:0.2as well asbilling_mode:tiered_exprand a token-based billing expression. - The 2.6 official-proxy dedicated page states token-based billing: $5 per million tokens for regular text input, $1.25 for cached text, $8 for regular image input, $2 for cached image, and $30 for output.
On the surface, these public sources don’t line up. So don’t treat $0.20 as a fixed actual charge. For how much an image really cost, go by your group, the usage for that specific request, and the actual charge shown in the console. The cost of model invocation should be accounted separately from operations like local saving and previewing.
💰 Cost check: You can first run a single-image request on APIYI apiyi.com using the same white porcelain cup prompt, then find that record in the console logs and see how much was actually charged. Using that number as the baseline for later batch image generation estimates is more reliable than directly applying the catalog list price.
5.3 A Rule You Can Apply Directly
If you need to generate a certain type of image every week using the same dimensions and naming rules, it’s worth spending half an hour setting up a local window. If you only make an image occasionally and need back-and-forth conversation to adjust it, sticking with a chat client is easier.
Once it’s set up, validate it this way: enter the white porcelain cup prompt and click Generate; the button should turn gray first; a PNG that opens normally should appear in the outputs directory; and the console should contain exactly one corresponding call record. If all three are satisfied, the first version is done. Later, if you want to add image editing, a custom directory picker, or metadata logging, you can extend this window step by step.
References
- APIYI GPT Image 2.6 Official Relay and Reverse Proxy: Sunburst billing, response fields, and channel differences
- Link:
docs.apiyi.com/en/api-capabilities/gpt-image-2/vs-gpt-image-2-6-all
- Link:
- Python Official Tkinter Documentation: windows, widgets, and main thread notes
- Link:
docs.python.org/3/library/tkinter.html
- Link:
- OpenAI Images in ChatGPT: uploading, editing, and image management in the chat client
- Link:
help.openai.com/en/articles/11084440-images-in-chatgpt
- Link:
Author: APIYI Technical Team
Technical Support: If you run into group, permission, or billing issues during integration, feel free to contact us via the APIYI homepage at apiyi.com.
