圖像生成
工具呼叫
讓聊天工具呼叫圖像生成,並顯示實際生成結果。
多語言 API 呼叫
執行方式見多語言範例說明。先設定 API_KEY,並替換模型、檔案網址及 ID 占位值;四種方式會顯示相同請求的原始回應。
此處顯示 API 原始回應;圖片的 Base64 解碼、下載與保存請接續本頁或圖像概覽的完整流程。 這是工具處理函式內的生成 API 呼叫,不是聊天端點;聊天回合的關聯 ID 處理見下方完整範例。
bash
curl --fail-with-body --silent --show-error --max-time 180 \
--request POST \
--url "https://api.tokatlas.ai/v1/images/generations" \
--header "Authorization: Bearer $API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "YOUR_ENABLED_IMAGE_MODEL_ID",
"prompt": "A white ceramic cup on a pale gray background, studio lighting",
"n": 1
}'python
import os
import requests
headers = {
'Authorization': 'Bearer ' + os.environ["API_KEY"],
'Content-Type': 'application/json',
}
payload = {'model': 'YOUR_ENABLED_IMAGE_MODEL_ID',
'prompt': 'A white ceramic cup on a pale gray background, studio lighting',
'n': 1}
response = requests.request(
'POST', 'https://api.tokatlas.ai/v1/images/generations', headers=headers,
json=payload,
timeout=180,
)
response.raise_for_status()
print(response.text)js
if (!process.env.API_KEY) throw new Error("Set API_KEY first.");
const response = await fetch("https://api.tokatlas.ai/v1/images/generations", {
method: "POST",
headers: {
"Authorization": "Bearer " + process.env.API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"model": "YOUR_ENABLED_IMAGE_MODEL_ID",
"prompt": "A white ceramic cup on a pale gray background, studio lighting",
"n": 1
}),
signal: AbortSignal.timeout(180_000),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
console.log(await response.text());java
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
public class Example {
public static void main(String[] args) throws Exception {
String apiKey = System.getenv("API_KEY");
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalArgumentException("Set API_KEY first.");
}
String payload = String.join("\n",
"{",
" \"model\": \"YOUR_ENABLED_IMAGE_MODEL_ID\",",
" \"prompt\": \"A white ceramic cup on a pale gray background, studio lighting\",",
" \"n\": 1",
"}"
);
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(30)).build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.tokatlas.ai/v1/images/generations"))
.timeout(Duration.ofSeconds(180))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IllegalStateException("HTTP " + response.statusCode() + ": "
+ response.body());
}
System.out.println(response.body());
}
}接入步驟
- 先跑通圖像生成概覽的生成及存檔範例,設定相同的
API_KEY與IMAGE_MODEL_ID。 - 開啟 Chat 工具呼叫 的完整 Python 範例,以以下定義取代
TOOLS的內容(保留外層列表)。 - 以本頁函式取代原本的
execute,並一併加入GENERATED_IMAGES。函式的 1,000 字限制是應用程式設定,不是所有模型的共同限制。 - 將 Chat 範例中「Check stock for DEMO-001.」的使用者訊息替換為生圖要求。成功時工具回報
completed與數量;使用概覽中的下載方式保存GENERATED_IMAGES,並由介面顯示圖片。
json
{"type":"function","function":{"name":"generate_image","description":"Generate an image and return its completion status.","parameters":{"type":"object","properties":{"prompt":{"type":"string","maxLength":1000}},"required":["prompt"],"additionalProperties":false}}}python
import os
import requests
GENERATED_IMAGES = []
def execute(name, args):
if name != "generate_image" or not isinstance(args, dict):
return {"error": "Invalid tool call"}
prompt = args.get("prompt")
if set(args) != {"prompt"} or not isinstance(prompt, str):
return {"error": "Expected a prompt string"}
if not prompt.strip() or len(prompt) > 1000:
return {"error": "prompt must contain 1 to 1000 characters"}
try:
response = requests.post(
"https://api.tokatlas.ai/v1/images/generations",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={"model": os.environ["IMAGE_MODEL_ID"], "prompt": prompt, "n": 1},
timeout=120,
)
except requests.RequestException:
return {"error": "Submission outcome unknown; reconcile before retrying"}
if not response.ok:
return {"error": "Submission failed; check before retrying",
"http_status": response.status_code}
body = response.json()
if not isinstance(body.get("data"), list) or not body["data"]:
return {"error": "Unexpected submission response; reconcile before retrying"}
images = body["data"]
if not all(item.get("url") or item.get("b64_json") for item in images):
return {"error": "Expected completed images; check the configured image route"}
# Store the actual images outside the model context; render them in your UI.
GENERATED_IMAGES.extend(images)
return {"status": "completed", "image_count": len(images)}不要把 Base64 圖片放入工具文字結果。正式應用請將結果存到每次請求各自的儲存空間,取代示範用的記憶體列表。超時時先核對請求記錄,避免對相同工具呼叫重複生成。
